An introduction to thread termination in JAVA

  • 2020-04-01 01:28:01
  • OfStack

In multithreaded programming in Java, the java.lang.thread type contains columns of methods start(), stop(), stop(), stop(Throwable) and suspend(), destroy() and resume(). With these methods, we can easily manipulate threads, but of these methods, only the start() method is retained.

The reasons for discarding these methods are explained in detail in a Sun article, "Why are thread.stop, thread.suspend and thread.resume Deprecated?"

If you really need to terminate a thread, you can use the following methods:
1. Let the thread's run() method execute to its natural end. (this is the best way)


2. End the thread by polling and sharing flag bits, for example, while(flag){}, the initial value of the flag is set to true, and the value of the flag is set to false when it needs to end. (this method is not good either, because if the while(flag){} method blocks, the flag will fail.)



public class SomeThread implements Runnable {
private volatile boolean stop = false;
public void terminate() {
stop = ture;
}
public void run() {
while(stop) {
// ... some statements
}
}
}

 

If a thread enters a Not Runnable state because it is performing sleep() or wait(), the wait() method will Not work.

Public final void wait(long timeout)
                              Throws InterruptedException this method causes the current thread (called T) to place itself in the wait set of an object and then abandon all synchronization requirements on that object. That is, the current thread becomes a wait state

Standard use of wait ()

Synchronized (obj) {

While (< Do not meet the conditions >) {

Obj. Wait ();

}

The process that satisfies the condition

}

And if you want to stop it, you can use the third

Using interrupt(), which throws InterruptedException to the program, thus causing the thread to leave the run() method,

Such as:

 


public class SomeThread {
public static void main(String[] args)
{
Thread thread=new Thread(new Runnable(){
 
public void run() {
 while (!Thread.interrupted()) {
                //Take care of the work to be done
                try {
                    
System.out.println("go to sleep");
Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                
System.out.println("i am interrupted!");
                }
});
thread.start();
thread.interrupt();
}
}

The execution result is:

Go to sleep.

I am interrupted!


Related articles: