java Thread 中断机制

来源:互联网 发布:条码打印软件使用方法 编辑:程序博客网 时间:2024/05/27 09:46

前段时间看见同事在代码里大量的使用java API中各种中断线程的方法,却不了解各种方法具体使用场景,很无语,故写篇博客分析一下。

在网上有很多人在问:java中怎样终止一个线程。以我现阶段的所了解的知识和方法,我还有没发现有什么其他的方法能够使一个正在运行的线程立即终止(可能还存在其他

的方法),javaAPI中的一些方法也只是唤醒线程而不是终止线程(API中很多方法已经不建议使用了,如:stop...) 如果想终止正常运行的线程,我所了解的唯一的方法就是使

该线程正常死亡。下面分析java API中的几个方法:interrupt(),interrupted(),isInterrupted()

interrupt():

很多人使用该方法去终止线程,但是这个方法根本就不能无法起作用,具体看下面的代码:

public class TestThread {private static boolean isStop = true;public static void main(String[] args) {Thread A = new Thread(new threadA());A.start();A.interrupt();}static class threadA implements Runnable{@Overridepublic void run() {while(isStop){System.out.println("我是线程A");try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("我快结束了");}}}


根据上图内容可知,线程A启动后,调用interrut方法,A线程没有终止,而是在抛出了InterruptedException异常后,依然正常执行,为什么呢?查看API可知:


也就是说如果该线程调用了wait(),wait(long), orwait(long, int)方法,或者join(),join(long),join(long, int),sleep(long), orsleep(long, int), 方法

该线程会抛出一个InterruptedException异常,而不是终止。

interrupted()

该方法是一个静态的返回值为boolean类型的方法,根据API中的解释:测试当前线程是否已经被中断,并且清除中断状态。当前中断状态为true如果调用两次该方法,第

二次调用后将返回false,原因是第二次调用时,线程的中断状态已经被第一次调用清除掉了(线程在第一次调用后再次被中断的情况除外)

isInterrupted()

该方法是检查当前线程的中断状态,调用该方法时不会影响线程的中断状态。

java API中的Thread.stop(),Thread.suspend(),Thread.resume()等方法都已经不赞成使用了,至于具体的原因可以仔细去研读API中的解释(会看文档的码农才是好码农)

怎样终止一个线程呢?归根到底就是让这个线程自然死亡,而不是人为终止。具体方法及使用场景如下:

第一:线程正处于休眠或阻塞状态,可以调用interrupt方法唤醒线程,然后让其自然死亡。

第二:线程处于循环状态,可以设置变量使其退出循环,从而自然死亡。

public class TestThread {private static volatile boolean isStop = false;public static void main(String[] args) {Thread B = new Thread(new threadB());B.start();TestThread.setStop(true);//设置循环退出标志为trueB.interrupt();//如果线程处在休眠状态,唤醒线程使其自然终止}static class threadB implements Runnable{@Overridepublic void run() {while(!isStop){System.out.println("我是线程B");try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("我快结束了");}}public static boolean isStop() {return isStop;}public static void setStop(boolean isStop) {TestThread.isStop = isStop;}}

参考链接:

http://redisliu.blog.sohu.com/131647795.html

http://polaris.blog.51cto.com/1146394/372146

http://www.blogjava.net/fhtdy2004/archive/2009/08/22/292181.html

http://bbs.chinaunix.net/thread-776492-1-1.html



原创粉丝点击