- 中断状态是线程的一个标识位,而中断操作是一种简便的线程间交互
方式,而这种交互方式最适合用来取消或停止任务。 除了中断以外,还可以利用一个boolean变量来控制是否需要停止任务并终止该线程。
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47public class ThreadShutdown {
public static void main(String[] args) throws InterruptedException {
Runner runner1 = new Runner("Runner1");
Thread thread1 = new Thread(runner1.runnable);
thread1.start();
//中断方式1
Thread.sleep(1);
thread1.interrupt();
Runner runner2 = new Runner("Runner2");
Thread thread2 = new Thread(runner2.runnable);
thread2.start();
Thread.sleep(1);
//中断方式2
runner2.shutdown();
}
4j
public static class Runner {
//关闭标记
private AtomicBoolean shutdown = new AtomicBoolean();
//自增
private AtomicInteger num = new AtomicInteger(0);
private String name = "Runner";
//运行
Runnable runnable = () -> {
//手动关闭
while (!shutdown.get() && !Thread.currentThread().isInterrupted()) {
num.incrementAndGet();
}
log.info("name:{},end:{}", name, num.get());
};
public Runner(String name) {
this.name = name;
}
//关闭
public void shutdown() {
shutdown.set(true);
}
}
}
执行结果
1 | [Thread-0] INFO ThreadShutdown$Runner - name:Runner1,end:4361 |
- main线程通过中断操作和shutdown()方法均可使Runner得以终止。
- 这种通过标识位或者中断操作的方式能够使线程在终止时有机会去清理资源,而不是武断地将线程停止,因此这种终止线程的做法显得更加安全和优雅。