How do I Stop/Suspend a Java Thread

If using  methods stop/suspend to stop a thread, this is unsafe and thus deprecated. If a thread being stopped now is modifying common data, that common data remains in an inconsistent state. However, 3 solutions is available as following:

1. let the method run() of the thread finishes itself, it’s best and have no any unsafe factors, for example:

public class OurThread extends Thread(){
   public void run(){
         System.out.println("ok")
   }
}

when the console output the string “OK”, this thread ends safely.

2. use a variable indication, in Thread, iterate this variable and check it, e.g while(flag){}, the indication can be modified outside, if it is modified, thread will be ended.

public class OurThread extends Thread(){
   private volatile boolean stop = false;
   public void run(){
       while (!stop) {
       //Do your actions
       }
   }
}

Set the variable stop to volatile, this make sure all reads and writes will go straight to “main memory”.

3. use interrupt() method and then catch InterruptedException to stop thread.

Оцените статью
ASJAVA.COM
Добавить комментарий

Your email address will not be published. Required fields are marked *