Java安全关闭线程
思路
- 思路1,利用中断标志关闭线程
- 思路2,利用volatile标识变量,线程间可见性共享。
实现1,利用中断关闭线程
public class DemoTest {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new Worker(), "demo-thread");
t.start();
Thread.sleep(500);
//中断子线程
System.out.println("=================> main thread execute interrupt");
t.interrupt();
// 等待子线程执行完毕
t.join();
System.out.println("=================> main thread end");
}
static class Worker implements Runnable {
private long i;
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()) {
i++;
System.out.println("=================> i value = " + i);
}
System.out.println("=================> finish i value = " + i);
}
}
}
实现2,利用volatile标识位关闭线程
public class DemoTest {
public static void main(String[] args) throws InterruptedException {
Worker worker = new Worker();
Thread t = new Thread(worker, "demo-thread");
t.start();
Thread.sleep(500);
//中断子线程
System.out.println("=================> main thread execute flag = false");
worker.closeThreadByFlag();
// 等待子线程执行完毕
t.join();
System.out.println("=================> main thread end");
}
static class Worker implements Runnable {
private long i;
private volatile boolean flag = true;
@Override
public void run() {
while(flag) {
i++;
System.out.println("=================> i value = " + i);
}
System.out.println("=================> finish i value = " + i);
}
public void closeThreadByFlag() {
flag = false;
}
}
}
参考
< Java并发编程的艺术 >