daemon:将线程设置为守护线程,调用线程结束后守护线程也跟着结束
join:调用join的线程只有结束后其他线程才会执行
interrupt:将线程中断,stop有风险被停用
结合join,interrupt和daemon暴力中断线
ThreadService
public class ThreadService {
private Thread excuteThread;
private boolean finished = false;
public void excute(Runnable runnable) {
excuteThread = new Thread() {
@Override
public void run() {
Thread inner = new Thread(runnable);
// 将inner设置成守护线程,这样调用它的线程结束后,inner线程也跟着结束
inner.setDaemon(true);
inner.start();
try {
// 执行完inner线程才会去执行别的线程,但是如果调用它的线程超时被中断,这个线程也会跟着中断
inner.join();
finished = true;
} catch (InterruptedException e) {
}
}
};
excuteThread.start();
}
public void shutdown(long mills) {
long current = System.currentTimeMillis();
while (!finished) {
// 系统当前时间-进入shutdown方法的时间,如果超时,直接中断
if ((System.currentTimeMillis()-current)>=mills) {
System.out.println("任务超时");
excuteThread.interrupt();
break;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
finished = false;
}
}
ThreadCloseForce
public class ThreadCloseForce {
private static volatile int i = 0;
public static void main(String[] args) {
ThreadService threadService = new ThreadService();
long start = System.currentTimeMillis();
threadService.excute(
() -> {
while (true) {
System.out.println(Thread.currentThread().getName() + "running..." + i++);
}
// try {
// Thread.sleep(5_000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
});
threadService.shutdown(8000);
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}