Go Ways to stop Java threads

Source: Internet
Author: User
Tags deprecated volatile

There are three ways to make a terminating thread.

1. Use the exit flag to cause the thread to exit normally, that is, the thread terminates when the Run method completes.

2. Use the Stop method to forcibly terminate the thread (this method is not recommended because stop and suspend, resume, can also cause unpredictable results). IS obsolete

3. Use the interrupt method to break the 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:

PrivateVolatile Thread blinker;
Publicvoid Stop () {
Blinker =null;
   }
    public void run () {
         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:

void Stop () {
Thread tmpblinker = blinker;
Null
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) {
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:

Package Com.cnblogs.gpcuster

Import java.net.*;
Import java.io.*;

PublicAbstractClass InterruptiblereaderExtends Thread {

Private Object lock =New Object ();
Private InputStream is;
PrivateBoolean done;
Privateint Buflen;
Protectedvoid ProcessData (Byte[] B,int n) {}

Class ReaderclassExtends Thread {

Publicvoid Run () {
Byte[] B =NewByte[buflen];

while (!done) {
try {
int n = is.read (b, 0, Buflen);
ProcessData (b, N);
}catch (IOException IoE) {
Done =True
}
}

Synchronized (lock) {
Lock.notify ();
}
}
}

Public Interruptiblereader (InputStream) {
This (IS, 512);
}

Public Interruptiblereader (InputStream is, int len) {
this.is = is;
Buflen = Len;
}

public Void Run () {
Readerclass rc = new Readerclass ();

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:

Package Com.cnblogs.gpcuster

Import Java.io.BufferedReader;
Import Java.io.FileDescriptor;
Import Java.io.FileInputStream;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.nio.channels.Channels;

PublicClass Interruptinput {
static BufferedReader in =New BufferedReader (
New InputStreamReader (
Channels.newinputstream (
(New FileInputStream (filedescriptor.in)). Getchannel ()));

PublicStaticvoid Main (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 Sec.) ");
Interrupt Input in ten SEC (New TimeOut ()). 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 class TimeOut extends Thread {
int sleeptime = 10000;
Thread threadtointerrupt = null;
public TimeOut () {
//interrupt thread that Creates this TimeOut. Threadtointerrupt = Thread.CurrentThread (); Setdaemon (true);
}

public void run () {
try {
Sleep (10000); //wait Ten sec} catch (Interruptedexception ex) {/*ignore*/}
Threadtointerrupt.interrupt ();
}
}
} /span>

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.

Resources

How to Stop a Thread or a Task

Why is Thread.stop, Thread.Suspend and Thread.Resume Deprecated?

Go Ways to stop Java threads

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.