In Java multithreaded programming, the Java.lang.Thread type contains some of the column's method start (), Stop (), Stop (Throwable) and suspend (), Destroy () and resume (). With these methods, we can easily manipulate threads, but only the start () method is preserved in these methods.
In a Sun company article "Why are Thread.stop, thread.suspend and Thread.Resume deprecated?" Explains the reasons for abandoning these methods in detail.
If you really need to terminate a thread, you can use the following methods:
1, let the thread's Run () method finished, the thread will naturally end. (This method is best)
2. End the thread by polling and sharing the flag bit, for example, while flag {},flag's initial value is set to True and the flag value is set to False when it needs to end. (This method is also not very good because if the while (flag) {} method is blocked, 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 the thread enters the not runnable state because of the execution of sleep () or wait (), the method will not work if the wait () is used with a flag bit.
Public final void Wait (long timeout)
Throws Interruptedexception
This method causes the current thread (called T) to place itself in the object's wait set, and then discard all synchronization requirements on this object. That is, the current thread becomes a wait state
Standard use method for Wait ()
Synchronized (obj) {
while (< does not meet condition >) {
Obj.wait ();
}
The process of satisfying a condition
}
And you want to stop it, you can use the third type
3 uses interrupt () and the program throws the interruptedexception exception so that the thread leaves 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 ()) {
Deal with the work to be done
try {
System.out.println ("Go");
Thread.Sleep (1000);
catch (Interruptedexception e) {
E.printstacktrace ();
System.out.println ("I am interrupted!");
}
});
Thread.Start ();
Thread.Interrupt ();
}
}
The results of the execution are:
Go to Sleep
I am interrupted!