Java多线程系列--“基础篇”09之 interrupt()和线程终止方式(六)

2014-11-24 03:21:45 · 作者: · 浏览: 15
etName() +" ("+t1.getState()+") is new.");
29
30 t1.start(); // 启动“线程t1”
31 System.out.println(t1.getName() +" ("+t1.getState()+") is started.");
32
33 // 主线程休眠300ms,然后主线程给t1发“中断”指令。
34 Thread.sleep(300);
35 t1.interrupt();
36 System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted.");
37
38 // 主线程休眠300ms,然后查看t1的状态。
39 Thread.sleep(300);
40 System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted now.");
41 } catch (InterruptedException e) {
42 e.printStackTrace();
43 }
44 }
45 }
复制代码
运行结果:
复制代码
t1 (NEW) is new.
t1 (RUNNABLE) is started.
t1 (RUNNABLE) loop 1
t1 (RUNNABLE) loop 2
t1 (TIMED_WAITING) is interrupted.
t1 (RUNNABLE) catch InterruptedException.
t1 (TERMINATED) is interrupted now.
复制代码
结果说明:
(01) 主线程main中通过new MyThread("t1")创建线程t1,之后通过t1.start()启动线程t1。
(02) t1启动之后,会不断的检查它的中断标记,如果中断标记为“false”;则休眠100ms。
(03) t1休眠之后,会切换到主线程main;主线程再次运行时,会执行t1.interrupt()中断线程t1。t1收到中断指令之后,会将t1的中断标记设置“false”,而且会抛出InterruptedException异常。在t1的run()方法中,是在循环体while之外捕获的异常;因此循环被终止。
我们对上面的结果进行小小的修改,将run()方法中捕获InterruptedException异常的代码块移到while循环体内。
复制代码
1 // Demo2.java的源码
2 class MyThread extends Thread {
3
4 public MyThread(String name) {
5 super(name);
6 }
7
8 @Override
9 public void run() {
10 int i=0;
11 while (!isInterrupted()) {
12 try {
13 Thread.sleep(100); // 休眠100ms
14 } catch (InterruptedException ie) {
15 System.out.println(Thread.currentThread().getName() +" ("+this.getState()+") catch InterruptedException.");
16 }
17 i++;
18 System.out.println(Thread.currentThread().getName()+" ("+this.getState()+") loop " + i);
19 }
20 }
21 }
22
23 public class Demo2 {
24
25 public static void main(String[] args) {
26 try {
27 Thread t1 = new MyThread("t1"); // 新建“线程t1”
28 System.out.println(t1.getName() +" ("+t1.getState()+") is new.");
29
30 t1.start(); // 启动“线程t1”
31 System.out.println(t1.getName() +" ("+t1.getState()+") is started.");
32
33 // 主线程休眠300ms,然后主线程给t1发“中断”指令。
34 Thread.sleep(300);
35 t1.interrupt();
36 System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted.");
37
38 // 主线程休眠300ms,然后查看t1的状态。
39 Thread.sleep(300);
40 System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted now.");
41 } catch (InterruptedException e) {
42 e.printStackTrace();
43 }
44 }
45 }
复制代码
运行结果:
复制代码
t1 (NEW) is new.
t1 (RUNNABLE) is started.
t1 (RUNNABLE) loop 1
t1 (RUNNABLE) loop 2
t1 (TIMED_WAITING) is interrupted.
t1 (RUNNABLE) catch InterruptedException.
t1 (RUNNABLE) loop 3
t1 (RUNNABLE) loop 4
t1 (RUNNABLE) loop 5
t1 (TIMED_WAITING) is interrupted now.
t1 (RUNNABLE) loop 6
t1 (RUNNABLE) loop 7
t1 (RUNNABLE) loop 8
t1 (RUNNABLE) loop 9
...
复制代码
结果说明:
程序进入了死循环!
为什么会这样呢?这是因为,t1在“等待(阻塞)状态”时,被interrupt()中断;此时,会清除中断标记[即isInterrupted()会返回false],而且