How to access the running thread/runnable?

后端 未结 5 878
我寻月下人不归
我寻月下人不归 2020-12-24 04:10

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 pub

5条回答
  •  既然无缘
    2020-12-24 04:45

    if you define it by class rather than as a Runnable you can call the instance methods.

    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

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

提交回复
热议问题