How to set an infinite loop and break it (java thread)

I've set up a thread and I want to run it using a loop Therefore, this thread should run in the loop, interrupt within a certain period of time and run the loop again

Please don't know how to do this Someone can guide me

Solution

Assuming that you are using JDK 1.5 or later (the memory model has been clarified and improved), you can use

public class MyRunnable extends Runnable
{
   private volatile boolean cancelled;

   public void run() {
      while (!cancelled) { 
         doStuff();
      }
   }

   public void cancel()
   {
      cancelled = true;  
   }

   public boolean isCancelled() {
      return cancelled;
   }
}j

Alternatively, use Java util. concurrent. Future and futuretask, which supports cancellation out of the box

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>