How to stop a Java thread

Source: Internet
Author: User
How to stop a Java thread

How to stop Java threads has always been a problem of annoyance when we develop multi-threaded programs. This question was finally answered in Java. util. Concurrent of Java 5: Use interrupt () to stop the thread in the run method.

Introduction

In Java multi-thread programming, Java. lang. the thread type includes the START (), stop (), stop (throwable) and suspend (), destroy () and resume () methods of some columns (). Through these methods, we can perform convenient operations on the thread, but among these methods, only the start () method is retained.

An article by Sun 《Why are thread. Stop, thread. Suspend and thread. Resume deprecated?The reason for dropping these methods is described in detail. So how should we stop the thread?

Recommended Method

In 《Why are thread. Stop, thread. Suspend and thread. Resume deprecated?To stop the thread:

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 more information about how to use the volatile keyword, see http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#30.

When the thread is not running

When the thread is in the following status, it is not running:

  • When the sleep method is called.

  • When the wait method is called.

  • When blocked by I/O, it may be a file or network.

When the thread is in the above state, the method described above is not available. At this time, we can use interrupt () to break the blocking situation, such:

public void stop() {        Thread tmpBlinker = blinker;        blinker = null;        if (tmpBlinker != null) {           tmpBlinker.interrupt();        }    }

When interrupt () is called, interruptedexception will be thrown, so you can catch this exception in the run method to exit the thread safely:

try {   ....   wait();} catch (InterruptedException iex) {   throw new RuntimeException("Interrupted",iex);}
Blocked I/O

When the thread is blocked by I/O, the call to interrupt () is dependent on the actual running platform. On Solaris and Linux platformsInterruptedioexceptionBut Windows does not. Therefore, we cannot rely on the implementation of the Platform to solve this problem. For example:

package com.cnblogs.gpcusterimport java.net.*;import java.io.*;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 = is.read(b, 0, buflen);                    processData(b, n);                } catch (IOException ioe) {                    done = true;                }            }            synchronized(lock) {                lock.notify( );            }        }    }    public InterruptibleReader(InputStream is) {        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) {}                }            }        }    }}

In addition, we can also use the interruptiblechannel interface. Classes that implement the interruptiblechannel interface can be thrown during blocking.ClosedByInterruptException. For example:

package com.cnblogs.gpcusterimport java.io.BufferedReader;import java.io.FileDescriptor;import java.io.FileInputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.nio.channels.Channels;public class InterruptInput {       static BufferedReader in = new BufferedReader(            new InputStreamReader(            Channels.newInputStream(            (new FileInputStream(FileDescriptor.in)).getChannel())));        public static void main(String args[]) {        try {            System.out.println("Enter lines of input (user ctrl+Z Enter to terminate):");            System.out.println("(Input thread will be interrupted in 10 sec.)");            // interrupt input in 10 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 10 sec            } catch(InterruptedException ex) {/*ignore*/}            threadToInterrupt.interrupt();        }    }}

Note that when the thread is in the file writing status, calling interrupt () will not interrupt the thread.

References

How to stop a thread or a task

Why are thread. Stop, thread. Suspend and thread. Resume deprecated?

Java threads, Third EditionO 'Reilly

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.