In Java multi-threaded programming, the java.lang.Thread type contains a series of methods start(), stop(), stop(Throwable) and suspend(), destroy() and resume(). Through these methods, we can perform convenient operations on threads, but among these methods, only the start() method is retained.
The reasons for abandoning these methods are explained in detail in an article by Sun "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 finish executing and the thread end naturally. (This method is the best)
2. End the thread by polling and sharing flag bits, such as while(flag){}, the initial value of flag is set to true, and when it needs to be terminated, set the value of flag to false. (This method is not very good either, because if the while(flag){} method blocks, the flag will become invalid)
private volatile boolean stop = false;
public void terminate() {
stop = true;
}
public void run() {
while(stop) {
// ... some statements
}
}
}
If the thread enters the Not Runnable state due to executing sleep() or wait(), if it is wait(), it will not work if the flag bit is used.
public final void wait(long timeout)
throws InterruptedException This method causes the current thread (call it T) to place itself in the object's wait set and then abandon all synchronization requirements on this object. That is, the current thread becomes a waiting state
Standard usage of wait()
synchronized(obj){
while(<condition not met>){
obj.wait();
}
Processing process that satisfies conditions
}
And you want to stop it, you can use the third one i.e.
3. Use interrupt(), and the program will throw an InterruptedException exception, thus causing the execution thread to leave the run() method.
For example:
public class SomeThread {
public static void main(String[] args)
{
Thread thread=new Thread(new Runnable(){
public void run() {
while (!Thread.interrupted()) {
// Process the work to be processed
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();
}
}
go to sleep
i am interrupted!