private volatile boolean isEnd = false;
private Thread slaveThread;
@GetMapping("/testThread")
public AjaxResult testThread() {
isEnd = false;
Thread thread = Thread.currentThread();
new Thread(new Runnable() {
@Override
public void run() {
while (!isEnd && !Thread.currentThread().isInterrupted()){
System.out.println("续费~~");
slaveThread = Thread.currentThread();
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// 在子线程sleep的时候,主线程调用slaveThread.interrupt();会使子线程抛出异常 sleep InterruptedException 所以需要再次中断
slaveThread.interrupt();
}
}
}
}).start();
for (int i = 0; i < 5; i++) {
try {
System.out.println("主线程~~");
thread.sleep(2000);
if (i == 4 && slaveThread != null){
if (slaveThread.isAlive()){
slaveThread.interrupt();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("主线程结束");
return null;
}
文章来源地址https://www.toymoban.com/news/detail-739353.html
文章来源:https://www.toymoban.com/news/detail-739353.html
到了这里,关于java 线程中止结合续期思想的小demo的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!