How to stop a Java thread
How to stop Java threads has always been a problem for us to develop multi-threaded software. The question was finally answered in Java5 's java.util.concurrent: Use Interrupt () to stop the thread from the Run method.
Brief introduction
In multithreaded programming in Java, the Java.lang.Thread type contains methods for some columns, 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 isthread.stop, thread.suspend and Thread.Resume Deprecated? " explains in detail the reasons for abandoning these methods. So how exactly should we stop the thread?
Suggested methods to use
In why isthread.stop, thread.suspend and Thread.Resume Deprecated? , we recommend that you use the following method to stop a thread:
PrivatevolatileThread Blinker;
PublicvoidStop () {
Blinker =NULL;
}
Public voidRun () {
Thread thisthread = Thread.CurrentThread ();
while(Blinker = = Thisthread) {
Try{
Thisthread.sleep (interval);
}Catch(Interruptedexception e) {
}
Repaint ();
}
}
For the reasons for using the volatile keyword, see http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#36930.
When the thread is in a non-running (run) state
When a thread is in the following state, it is non-operational:
When the sleep method is called.
When the wait method is called.
When I am blocked by I/O, it may be file or network, etc.
When the thread is in the above state, using the method described earlier is not available. At this time, we can use interrupt () to break the blocking situation, such as:
Public void Stop () {
Thread tmpblinker = blinker;
null;
if null) {
Tmpblinker.interrupt ();
}
}
When interrupt () is called, Interruptedexception will be thrown, so you can catch this exception in the Run method and let the thread safely exit:
Try {
....
Wait ();
Catch (Interruptedexception IEX) {
Throw New RuntimeException ("interrupted", IEX);
}
Blocked I/O
When a thread is blocked by I/O, the case of calling interrupt () is dependent on the actual running platform. interruptedioexception Exceptions will be thrown on the Solaris and Linux platforms, but there is no such exception on Windows. Therefore, we can not deal with this problem depends on the implementation of the platform. Such as:
PackageCom.cnblogs.gpcuster
Importjava.net.*;
Importjava.io.*;
Public Abstract classInterruptiblereaderextendsThread {
PrivateObject lock =NewObject ();
PrivateInputStream is;
Private BooleanDone
Private intBuflen;
protected voidProcessData (byte[] B,intN) {}
classReaderclassextendsThread {
Public voidRun () {
byte[] B =New byte[Buflen];
while(!done) {
Try{
intn = is.read (b, 0, Buflen);
ProcessData (b, N);
}Catch(IOException IoE) {
Done =true;
}
}
synchronized(lock) {
Lock.notify ();
}
}
}
PublicInterruptiblereader (InputStream is) {
This(IS, 512);
}
PublicInterruptiblereader (InputStream is,intLen) {
This. is = is;
Buflen = Len;
}
Public voidRun () {
Readerclass rc =NewReaderclass ();
synchronized(lock) {
Rc.start ();
while(!done) {
Try{
Lock.wait ();
}Catch(Interruptedexception IE) {
Done =true;
Rc.interrupt ();
Try{
Is.close ();
}Catch(IOException IoE) {}
}
}
}
}
}
Alternatively, we can also use the Interruptiblechannel interface. Classes that implement the Interruptiblechannel interface can be thrown when blocking ClosedByInterruptException
. Such as:
PackageCom.cnblogs.gpcuster
ImportJava.io.BufferedReader;
ImportJava.io.FileDescriptor;
ImportJava.io.FileInputStream;
ImportJava.io.InputStream;
ImportJava.io.InputStreamReader;
ImportJava.nio.channels.Channels;
Public classInterruptinput {
StaticBufferedReader in =NewBufferedReader (
NewInputStreamReader (
Channels.newinputstream (
(NewFileInputStream (filedescriptor.in)). Getchannel ()));
Public Static voidMain (String args[]) {
Try{
System.out.println ("Enter lines of input (user Ctrl + Z Enter to terminate):");
System.out.println ("(Input thread would be interrupted in the SEC.)");
//Interrupt Input in ten SEC(NewTimeOut ()). Start ();
String line =NULL;
while(line = In.readline ())! =NULL) {
System.out.println ("Read line: '"+line+"'");
}
}Catch(Exception ex) {
System.out.println (Ex.tostring ());//Printstacktrace ();} } Public Static classTimeOutextendsThread {
intSleeptime = 10000;
Thread Threadtointerrupt =NULL;
PublicTimeOut () {
//Interrupt thread that creates this TimeOut.Threadtointerrupt = Thread.CurrentThread (); Setdaemon (true);
}
Public voidRun () {
Try{
Sleep (10000);//wait ten sec}Catch(Interruptedexception ex) {/*ignore*/}
Threadtointerrupt.interrupt ();
}
}
}
It is also important to note that when the thread is in the state of the write file, the call to interrupt () does not break thread.
Source: >
From for notes (Wiz)
How to stop a Java thread