测试代码
public static void main(String[] args) throws InterruptedException {
TPTInterrupt t = new TPTInterrupt();
TPTVolatile t1 = new TPTVolatile();
t.start();
Thread.sleep(3500);
MyTool.printTimeAndThread("停止线程...");
t.stop();
}
示意图
方式一:使用打断方式停止线程
示例代码
static class TPTInterrupt {
private Thread thread;
public void start(){
thread = new Thread(() -> {
while(true) {
Thread current = Thread.currentThread();
if(current.isInterrupted()) {
MyTool.printTimeAndThread("退出前业务逻辑处理");
break;
}
try {
Thread.sleep(1000);
MyTool.printTimeAndThread("业务逻辑处理结束");
} catch (InterruptedException e) {
MyTool.printTimeAndThread("阻塞时被打断,执行interrupt()方法前,此时打断状态为:"+ current.isInterrupted());
current.interrupt();
MyTool.printTimeAndThread("阻塞时被打断,执行interrupt()方法后,此时打断状态为:"+ current.isInterrupted());
}
}
},"业务线程");
thread.start();
}
public void stop() {
thread.interrupt();
}
}
方式二:使用volatile保证多线程间变量的可见性实现
static class TPTVolatile {
private Thread thread;
private volatile boolean stop = false;
public void start() {
thread = new Thread(() -> {
while (true) {
if (stop) {
MyTool.printTimeAndThread("退出前业务逻辑处理");
break;
}
try {
Thread.sleep(1000);
MyTool.printTimeAndThread("业务逻辑处理结束");
} catch (InterruptedException e) {
MyTool.printTimeAndThread("睡眠时被打断");
}
}
}, "业务线程");
thread.start();
}
public void stop() {
stop = true;
thread.interrupt();
}
}