简体   繁体   English

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

[英]How to access the running thread/runnable?

I have a thread running but from outside I can't bypass a value to stop that thread. 我有一个线程正在运行,但从外面我不能绕过一个值来停止该线程。 How can I send false/true value inside Mytest() or call running thread public methods? 如何在Mytest()发送false / true值或调用运行的线程公共方法? When I press the button1? 当我按下按钮1? ex: thread.interrupt(); 例如: thread.interrupt(); runnable.stop(); or runnable.start(); 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; }
}

Follow up (proof read): 跟进(校对):

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;}
}

if you define it by class rather than as a Runnable you can call the instance methods. 如果您按类而不是Runnable定义它,则可以调用实例方法。

public static Mytest runnable;

Also note that due to multiple cores having their own associated memory, you need to warn the processor that the state may be changed on another processor and that it needs to watch for that change. 另请注意,由于多个内核具有自己的关联内存,因此需要警告处理器可能会在另一个处理器上更改状态,并且需要注意该更改。 Sounds complicated, but just add the 'volatile' keyword to the boolean flags 听起来很复杂,但只需将'volatile'关键字添加到布尔标志中

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

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

  public void stop() { running = false;}
}

Start the Runnable as in your initial code, then shut it down using runnable.stop() 像在初始代码中一样启动Runnable ,然后使用runnable.stop()其关闭

You should always use the interrupt method to stop a thread. 您应该始终使用中断方法来停止线程。 This is a safe and the adequate way to perform a stop operation an a thread. 这是一种安全且适合执行线程停止操作的方法。

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();

And when you would like to stop you thread just invoke the interrupt method: 当你想停止线程时,只需调用中断方法:

tThread.interrupt();

public void run()
  {
    while(!isInterrupted()) {
      if (onoff) {
         return;
       } else { 
         if (status==false) System.out.println("running"); 
       }
    }
  }

Then use Thread.interrupt() to indicate a interrption of the thread. 然后使用Thread.interrupt()来指示线程的交叉。

Note: Don't use Thread.stop() under any circumstance ! 注意: 在任何情况下都不要使用Thread.stop() It's Deprecated ! 它已经弃用了
For more detail, JDK document and << Java Concurrency in Practice >> can be referred to. 有关更多详细信息,可以参考JDK文档和<< Java Concurrency in Practice >>。

in your run method... 在你的运行方法中......

dont do while(true).. 不要做(真)..

use a boolean... like... while(threadIsRunning) 使用布尔...比如... while(threadIsRunning)

and this boolean you can set to true/false.... 这个布尔值你可以设置为true / false ....

Apart from the fact, that this thread is a heating test for your CPU ;) 除了这个事实,这个线程是你的CPU的加热测试;)

You can call the start/stop methods with 您可以使用调用启动/停止方法

 MyThread.start();
 MyThread.stop();

You've defined them as static methods, so the above lines of code show how to call them. 您已将它们定义为static方法,因此上面的代码行显示了如何调用它们。

for the heating... add something like 加热...添加类似的东西

try {
    Thread.sleep(100);  // value is milliseconds
} catch (InterruptedException e) {
    // no need to handle (in this example)
}

This will reduce the CPU load from 100% (on one core) to a reasonable value ;) 这会将CPU负载从100%(在一个核心上)减少到合理的值;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM