Java多线程系列--“基础篇”09之 interrupt()和线程终止方式(三)
法中,是在循环体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],而且会抛出InterruptedException异常[该异常在while循环体内被捕获]。因此,t1理所当然的会进入死循环了。
解决该问题,需要我们在捕获异常时,额外的进行退出while循环的处理。例如,在MyThread的catch(InterruptedException)中添加break 或 return就能解决该问题。
下面是通过“额外添加标记”的方式终止“状态状态”的线程的示例:
复制代码
1 // Demo3.java的源码
2 class MyThread extends Thread {
3
4 private volatile boolean flag= true;
5 public void stopTask() {
6 flag = false;
7 }
8
9 public MyThread(String name) {
10 super(name);
11 }
12
13 @Override
14 public void run() {
15 synchronized(this) {
16 try {
17 int i=0;
18 while (flag) {
19 Thread.sleep(100); // 休眠100ms
20 i++;
21 System.out.println(Thread.currentThread().getName()+" ("+this.getState()+") loop " + i);
22 }
23 } catch (InterruptedException ie) {
24 System.out.println(Thread.currentThread().getName() +" ("+this.getState()+") catch InterruptedException.");
25 }
26 }
27 }
28 }
29
30 public class Demo3 {
31
32 public static void main(String[] args) {
33 try {
34 MyThread t1 = new MyThread(