1.2.5 安全的终止线程

Java 并发编程的艺术第2版学习笔记

原书:《Java 并发编程的艺术第2版》 | 作者:方腾飞 魏鹏 程晓明 | 2023 年 9 月 | 机械工业出版社

使用 interrupt()标识位终止线程,使线程在终止时有机会清理资源,因此更加安全优雅。

代码示例

 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
30
31
32
33
34
35
public class Shutdown {

    public static void main(String[] args) {
        Thread countThread = new Thread(new Runner(), "使用 interrupt() 来终止线程");
        countThread.start();
        // 睡眠 1 秒,main 线程对 CountThread 进行中断,使 CountThread 能够感知中断而结束
        SleepUtils.second(1);
        countThread.interrupt();

        Runner runner = new Runner();
        countThread = new Thread(runner, "使用 on 标识来终止线程");
        countThread.start();
        // 睡眠 1 秒,main 线程对 CountThread 进行取消,使 CountThread 能够感知 on 为 false 而结束
        SleepUtils.second(1);
        runner.cancel();
    }

    private static class Runner implements Runnable {
        private long i;
        private volatile boolean on = true;

        @Override
        public void run() {
            while (on && !Thread.currentThread().isInterrupted()) {
                i++;
            }
            System.out.println(Thread.currentThread().getName() + " Count i = " + i);
        }

        public void cancel() {
            on = false;
        }
    }

}

SleepUtils

1
2
3
4
5
6
7
8
9
class SleepUtils {
    static void second(long seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
comments powered by Disqus