如何访问正在运行的线程/ runnable?

9 java

我有一个线程正在运行,但从外面我不能绕过一个值来停止该线程.如何在内部发送false/true值Mytest()或调用运行线程公共方法?当我按下按钮1?例如:thread.interrupt(); runnable.stop();runnable.start();

// Main
public class Main extends JFrame
{
  public static Runnable runnable;
  public static Thread thread;
  private JButton b1    = new JButton("Start/Stop");

  public void init() 
  {    
    //Execute a job on the event-dispatching thread:
    try {
       javax.swing.SwingUtilities.invokeAndWait(new Runnable() 
       {
         public void run() 
         {
            createGUI();
         }
        });
     } catch (Exception e) { 
       System.err.println("createGUI didn't successfully complete");
     }
  }

  public void createGUI()
  {
    Container cp = getContentPane();
    b1.addActionListener(new button1()); cp.add(b1);
    runnable = new Mytest();
    thread = new Thread(runnable);
    thread.start();
  }
}

// Button 1 - [problem to go  inside a running thread]
public class button1 implements ActionListener 
{
  public void actionPerformed(ActionEvent e) 
  {
    System.out.println("button pressed - need to access ");
      //thread.interrupt();       runnable.stop(); //or runnable.start();
  }
}

// Running - Thread
public class Mytest implements Runnable
{
  public static boolean onoff = false;
  public static boolean status = false;

  public void run()
  {
    while(true) 
    {
      if (onoff) 
      {
         return;
       } else { 
         if (status==false) System.out.println("running"); 
       }
    }
  }
  public static void stop() { status = true; onoff=true; }
  public static void start() { status = false; onoff = false; }
}
Run Code Online (Sandbox Code Playgroud)

跟进(校对):

Step 1:

/* Main -  boot/startup */
public class Main extends JFrame
{
    public static Mytest runnable;  // wrong: public static Runnable runnable;
    public static Thread thread;
    private JButton b1    = new JButton("Start");
    private JButton b2    = new JButton("Stop");  

  public void init() 
  {    
    // Execute a job on the event-dispatching thread:
    // In case Freezed for heavy lifting
    try {
       javax.swing.SwingUtilities.invokeAndWait(new Runnable() 
       {
         public void run() 
         {
            createGUI();
         }
       });
     } catch (Exception e) { 
       System.err.println("createGUI didn't successfully complete");
     }
  }

  public void createGUI()
  {
    Container cp = getContentPane();
    b1.addActionListener(new button1()); 
    cp.add(b1);

    runnable = new Mytest();
    thread = new Thread(runnable);    
        try {
                thread.sleep(100);  // value is milliseconds        
                thread.start();     
        } catch (InterruptedException e) {              
        }
  }

  public static void main(String[] args)
  {        
    run(new Main(), 500, 500);
  }

  public static void run(JFrame frame, int width, int height) 
  {        ...
    frame.setVisible(true);
  }
}

/* To start */
public class button1 implements ActionListener 
{
  public void actionPerformed(ActionEvent e) 
  {
    runnable.start();
  }    
}

/* To stop */
public class button2 implements ActionListener 
{
  public void actionPerformed(ActionEvent e) 
  {
    runnable.stop();
  }    
}

Step 2:

/* Thread deals */
public class Mytest implements Runnable
{
  private static volatile boolean running = true;

  public void run()
  {
    while(running) 
    {
      // do stuff
    }
  }
  public void start() { running = true; }
  public void stop()  { running = false;}
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*ara 7

如果你按类而不是Runnable你可以调用实例方法来定义它.

public static Mytest runnable;
Run Code Online (Sandbox Code Playgroud)

另请注意,由于多个内核具有自己的关联内存,因此需要警告处理器可能会在另一个处理器上更改状态,并且需要注意该更改.听起来很复杂,但只需将'volatile'关键字添加到布尔标志中

public class Mytest implements Runnable
{
  private static volatile boolean running = true;

  public void run()
  {
    while(running) {
      // do stuff
    }
  }

  public void stop() { running = false;}
}
Run Code Online (Sandbox Code Playgroud)

Runnable在初始代码中启动as,然后使用将其关闭runnable.stop()

  • 当`run`方法结束时,线程停止.如果需要,可以将Mytest实例附加到新线程,或者如果要再次运行它,可以在现有线程上调用`start()`.此代码只是确保正在运行的代码将在合理的时间范围内完成(如果标志不是volatile,则不是这种情况) (3认同)
  • `new Runnable()`只是一种创建匿名类的简便方法,它可以在不明确声明类的情况下实现Runnable.如果要在其他地方访问该类,则将其声明为实现Runnable的类,具有相同的方法,然后在代码中创建可用于执行其他操作的实例. (2认同)

Rob*_*und 6

您应该始终使用中断方法来停止线程.这是一种安全且适合执行线程停止操作的方法.

Thread tThread = new Thread(new Runnable() {

                public void run() {
                        while (!Thread.currentThread().isInterrupted()) {
                        try{
                        Thread.sleep(10);
                        ... do you stuff...
                        }catch(InterruptedException ex){

                            break;
                        }
                    }

                }

            });
    tThread.start();
Run Code Online (Sandbox Code Playgroud)

当你想停止线程时,只需调用中断方法:

tThread.interrupt();
Run Code Online (Sandbox Code Playgroud)