存在监控线程,日志线程等需要同主线程一同存在与退出,那么如何在主线程退出前正确优雅的结束这些子线程?
因为stop方法(以及用于暂停的suspend)都不能释放资源而导致死锁等问题已经弃用,这里只讨论优雅的退出方式。
共享变量控制法
import java.util.concurrent.TimeUnit;
public class TerminationThread {
private volatile boolean run;
public void start(){
run = true;
new Thread(() -> {
while (run) {
try {
System.out.println("处理事务");
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("结束前后续处理步骤");
}).start();
}
public void stop(){
run = false;
}
public static void main(String[] args) throws InterruptedException {
TerminationThread terminationThread = new TerminationThread();
terminationThread.start();
TimeUnit.SECONDS.sleep(5);
terminationThread.stop();
}
}
打断(interrupt)的方法
import java.util.concurrent.TimeUnit;
public class TerminationThread3 {
private Thread t;
public void start() {
t = new Thread(() -> {
while (true) {
if (t.isInterrupted()) {
System.out.println("结束前后续处理步骤");
break;
}
try {
System.out.println("处理事务");
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
t.interrupt();//睡眠中被打断会清楚打断标记,这里补上标记让下个循环开始退出
}
}
}, "t");
t.start();
}
public void stop() {
t.interrupt();
}
public static void main(String[] args) throws InterruptedException {
TerminationThread3 terminationThread3 = new TerminationThread3();
terminationThread3.start();
TimeUnit.SECONDS.sleep(5);
terminationThread3.stop();
}
}
守护线程(没有办法释放资源,但可以让子线程随主线程一同结束,可以容忍后续步骤不完成的情况下使用)
import java.util.concurrent.TimeUnit;
public class TerminationThread2 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
while (true) {
try {
System.out.println("处理事务");
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
TimeUnit.SECONDS.sleep(5);
}
}
网友评论