JAVA7多线程只interrupt方法

来源:互联网 发布:mac移除应用 编辑:程序博客网 时间:2024/06/06 05:43

今天开始学习《java7并发编程实践》,在学习interrupt方法时,有这么一个案例:共涉及到2个类:

FileLock类:

public class FileLock implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.printf("now is %s \n",new Date());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.println("ooooo, i am filelock , i was interrupted ");
}
}
}
}

FileLockTest类:

public class FileLockTest {
public static void main(String[] args) {
Thread thread = new Thread(new FileLock());
thread.start();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {

System.out.println(" will my words be printed???????????");
}
thread.interrupt();
}
}


按照我预期,将会在控制台 每隔1秒,打印出当前日期,将打印出5次。因为在执行到FileLock线程在执行5秒时,被interrupt 后。

但程序的运行结果却是:

now is Sat Jun 17 16:42:17 CST 2017
now is Sat Jun 17 16:42:18 CST 2017
now is Sat Jun 17 16:42:19 CST 2017
now is Sat Jun 17 16:42:20 CST 2017
now is Sat Jun 17 16:42:21 CST 2017
ooooo, i am filelock , i was interrupted
now is Sat Jun 17 16:42:22 CST 2017
now is Sat Jun 17 16:42:23 CST 2017
now is Sat Jun 17 16:42:24 CST 2017
now is Sat Jun 17 16:42:25 CST 2017
now is Sat Jun 17 16:42:26 CST 2017


说明程序在innterrupt 后,程序并没有终止,还是继续往下走了。

在百度后,有这么一个解释:

首先,每个线程内部都有一个boolean型变量表示线程的中断状态,true代表线程处于中断状态,false表示未处于中断状态。

而interrupt()方法的作用只是用来改变线程的中断状态(把线程的中断状态改为true,即被中断)。

抛出InterruptedException以后,线程又会回到非中断状态(false)。

因此interrupt()方法代表着外界希望中断此线程,只是希望,具体怎么处理还是线程内部来做,一般情况下interrupt()方法可以使处于阻塞状态的线程抛出InterruptedException从而结束阻塞状态。

看了此解释,似乎可以解释以上的例子的运行结果。

但是我并没有从源代码上得到佐证。

先留此贴,待日后,找到原因后,再来补充。

看到的网友,如能解释的,望不吝赐教!

原创粉丝点击