设置一个守护线程,和一个执行线程,让守护线程去执行逻辑,超时后中断执行线程,守护线程也随之中断。
/**
* @author Livingdd
* 设置一个执行线程和一个守护线程,让守护线程去执行
* 2019/11/14 21:43
**/
public class ThreadService {
private Thread excuteThread;
private boolean finshed = false;
public void excute(Runnable task){
excuteThread = new Thread(){
@Override
public void run() {
Thread runner = new Thread(task);
runner.setDaemon(true);
runner.start();
try {
runner.join();
finshed = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
excuteThread.start();
}
public void shutDown(long mills){
long currentTime = System.currentTimeMillis();
while(!finshed){
if(System.currentTimeMillis() - currentTime >= mills){
excuteThread.interrupt();
}
try {
excuteThread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}