Java Shutdown Thread Detailed __java

Source: Internet
Author: User
Tags deprecated static class thread class thread stop volatile

Go to:

Three ways to terminate a thread

There are three ways to terminate the 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 force a thread to terminate (this method is not recommended because it can also occur unpredictable results, as with suspend, resume).

3. Use the interrupt method to disconnect threads.
1. Terminate thread with Exit flag

When the Run method finishes executing, the thread exits. But sometimes the run method is never going to end. such as using threads in a server-side program to listen for client requests, or other tasks that need to be cycled. In this case, you typically put these tasks in a loop, such as a while loop. If you want the loop to run forever, you can use the while (True) {...} To deal with. But the most straightforward way to get the while loop to exit under a certain condition is to set a Boolean flag and control whether the while loop exits by setting the flag to true or false. An example of terminating a thread with an exit flag is given below.

Package chapter2;

public class Threadflag extends Thread
Public volatile Boolean exit = FALSE;

public void Run ()
while (!exit);
public static void Main (string[] args) throws Exception
Threadflag thread = new Threadflag ();
Thread.Start ();
Sleep (5000); Main thread delay 5 seconds
Thread.exit = true; Terminating thread Threads
Thread.Join ();
SYSTEM.OUT.PRINTLN ("Thread exit!");

An exit flag exit is defined in the above code, and when exit is true, the while loop exits, The default value for Exit is false. When you define exit, you use a Java keyword volatile, which is designed to synchronize exit, meaning that only one thread can modify the exit value at the same time.

2. Terminate a thread using the Stop method

Use the Stop method to forcibly terminate a running or suspended thread. We can terminate the thread by using the following code:

Thread.stop ();

Although using the above code to terminate a thread, it is dangerous to use the Stop method, which may produce unpredictable results when you suddenly turn off the computer instead of shutting down the normal program, and therefore it is not recommended that you terminate the thread with the Stop method.

3. Terminating a thread using the interrupt method

Using the interrupt method to end threads can be divided into two scenarios:

(1) The thread is in a blocking state, such as using the Sleep method.

(2) using the while (. Isinterrupted ()) {...} To determine if the thread was interrupted.

In the first case, using the interrupt method, the sleep method throws a Interruptedexception exception, and in the second case the thread exits directly. The following code demonstrates the use of the interrupt method in the first case.

Package chapter2;

public class Threadinterrupt extends Thread
public void Run ()
Sleep (50000); Delay 50 seconds
catch (Interruptedexception e)
System.out.println (E.getmessage ());
public static void Main (string[] args) throws Exception
Thread thread = new Threadinterrupt ();
Thread.Start ();
System.out.println ("Press any key within 50 seconds to disconnect thread!"); ();
Thread.Interrupt ();
Thread.Join ();
SYSTEM.OUT.PRINTLN ("Thread has exited!");

The results of the above code run as follows:

Press any key within 50 seconds to disconnect the thread!

Sleep interrupted
The thread has exited!

After the interrupt method is invoked, the sleep method throws an exception and then prints an error message: Sleep interrupted.

Note: There are two methods in the thread class to determine whether a thread is terminated by the interrupt method. One is static method interrupted (), a non-static method isinterrupted (), the difference between the two methods is that interrupted is used to determine whether the current line is interrupted and isinterrupted can be used to determine if other threads are interrupted. Therefore, while (. Isinterrupted ()) can also be replaced with a while (. Thread.interrupted ()).
How to stop Java threads

How to stop a Java thread has been a problem for us to develop multithreaded programming. The problem was eventually answered in Java5 's java.util.concurrent: Use Interrupt () to let the thread stop in the Run method. Brief Introduction

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. So how exactly should we stop the thread? suggested methods of use

In the Why are Thread.stop, thread.suspend and Thread.Resume deprecated? , we recommend that you stop the thread by using the following methods:

private volatile Thread blinker;
public void Stop () {
Blinker = null;
public void Run () {
Thread thisthread = Thread.CurrentThread ();
while (blinker = = Thisthread) {
try {
Thisthread.sleep (interval);
catch (Interruptedexception e) {
Repaint ();

For a reason to use the volatile keyword, see when a thread is in a non-running (run) state

When a thread is in the following state, it is not running:

When the sleep method is invoked.

When the wait method is invoked.

When blocked by I/O, it may be a file or network, and so on.

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;
        Blinker = null;
        if (Tmpblinker!= null) {
           tmpblinker.interrupt ();

When interrupt () is called, the interruptedexception is thrown, so you can catch the 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 call to interrupt () is dependent on the actual running platform. Interruptedioexception exceptions will be thrown on 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. For example,

Package Com.cnblogs.gpcuster import*;

    Public abstract class Interruptiblereader extends Thread {private Object lock = new Object ();
    Private InputStream is;
    private Boolean done;
    private int buflen;
            protected void ProcessData (byte[] B, int n) {} class Readerclass extends Thread {public void run () {

            Byte[] B = new Byte[buflen];
                    while (!done) {try {int n = (b, 0, Buflen);
                ProcessData (b, N);
                catch (IOException IoE) {done = true;
            } synchronized (lock) {lock.notify ();
    }} public Interruptiblereader (InputStream are) {This (IS, 512);
        Public Interruptiblereader (InputStream are, int len) { = 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 (); The catch (IOException IoE) {}}}}

In addition, we can also use the Interruptiblechannel interface. A class that implements the Interruptiblechannel interface can throw closedbyinterruptexception when it is blocked. Such as:

Package Com.cnblogs.gpcuster import;

Import Java.nio.channels.Channels;
            public class Interruptinput {static BufferedReader in = new BufferedReader (New InputStreamReader (
    Channels.newinputstream ((New FileInputStream ( Getchannel ())); public static void Main (String args[]) {try {System.out.println ("Enter Lines of input" (User Ctrl+z E
            Nter to terminate): ");
            System.out.println ("(Input thread would be interrupted in Sec.)");
            Interrupt Input in SEC (new TimeOut ()). Start ();
            String line = null;
            while (line = In.readline ())!= null) {System.out.println ("Read line: ' +line+ '"); The 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 ' creates this TimeOut.
            Threadtointerrupt = Thread.CurrentThread ();
        Setdaemon (TRUE); public void Run () {try {10000);//The Wait sec} catch ( Interruptedexcept

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: 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.