线程的中断机制 | 张扎瓦的博客

线程的中断机制


调用Thread.stop()

该方法强迫停止一个线程,并抛出一个新创建的ThreadDeath对象作为异常。然而,Thread.stop()不安全,已不建议使用。

使用Thread.interrupt()

  Java中断机制是一种协作机制,也就是说通过中断并不能直接终止另一个线程,而需要被中断的线程自己处理中断。

  Java中断模型也可以简单做如下理解,每个线程对象里都有一个boolean类型的标识,代表着是否有中断请求(该请求可以来自所有线程,包括被中断的线程本身)。例如:当线程t1想中断线程t2,只需要在线程t1中将线程t2对象的中断标识置为true,然后线程t2可以选择在合适的时候处理该中断请求,甚至可以不理会该请求,就像没有被中断一样。

Thread类中关于中断的方法:

  • public boolean isInterrupted():测试线程是否已经中断。
  • public void interrupt():中断线程。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class ThreadTest2 {
public static void main(String[] args) throws InterruptedException {
Runnable runnable = () -> {
boolean stop = true;
while (stop) {
System.out.println("thread is running...");
long time = System.currentTimeMillis();
// 延时1s
while (System.currentTimeMillis() - time < 1000) {

}
}
};

Thread thread = new Thread(runnable, "test Thread");
System.out.println("启动线程");
thread.start();

Thread.sleep(3000);
thread.interrupt(); // 中断线程
System.out.println("线程是否中断:" + thread.isInterrupted());
}
}

输出结果如下:

1
2
3
4
5
6
7
8
9
10
启动线程
thread is running...
thread is running...
thread is running...
thread is running...
线程是否中断:true
thread is running...
thread is running...
thread is running...
......

从运行结果上看,线程并没有结束,因为线程2并没有处理该中断请求。接下来,我们对例子稍加改进:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class ThreadTest2 {
public static void main(String[] args) throws InterruptedException {
Runnable runnable = () -> {
boolean stop = true;
while (stop) {
System.out.println("thread is running...");
long time = System.currentTimeMillis();
// 延时1s
while (System.currentTimeMillis() - time < 1000) {

}
// 注意这里 ====================
if (Thread.currentThread().isInterrupted()) {
System.out.println("线程中断后退出");
break;
}
// 注意这里 ====================
}
};

Thread thread = new Thread(runnable, "test Thread");
System.out.println("启动线程");
thread.start();

Thread.sleep(3000);
thread.interrupt(); // 中断线程
System.out.println("线程是否中断:" + thread.isInterrupted());
}
}

输出结果如下:

1
2
3
4
5
6
7
启动线程
thread is running...
thread is running...
thread is running...
thread is running...
线程是否中断:true
线程中断后退出

此时线程2才真正终止结束了。

注意

  如果线程处在可中断状态下(调用了Thread.wait()或者Thread.sleep()等特定会发生阻塞的api),那么该线程会被立即唤醒,同时抛出一个InterruptedException。简单的异常处理如下:

1
2
3
4
5
6
7
8
9
10
11
Runnable runnable = () -> {
boolean stop = true;
while (stop) {
System.out.println("thread is running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
};
如果我的文章对您有所帮助,不妨打赏一杯豆浆以资鼓励(○` 3′○)