线程池 某一个线程任务超时,如何真正取消正在执行的线程呢?
直接上代码吧
方案1:
static class WarpFeature<T> {
Future<T> f;
String name;
public WarpFeature(Future<T> f, String name) {
this.f = f;
this.name = name;
}
}
@Test
public void s1_1_cancle() {
Logger log = LoggerFactory.getLogger(TestThread.class);
ExecutorService executorService = new ThreadPoolExecutor(1, 1, 1L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1), r -> new Thread(r, "测试线程")
, new ThreadPoolExecutor.DiscardPolicy());
List<WarpFeature<Object>> futures = new ArrayList<>();
futures.add(new WarpFeature<>(executorService.submit(() -> {
boolean flag = true;//只是模拟条件用
Thread threadNow = Thread.currentThread();
long time = System.currentTimeMillis();
int i = 0;
while (flag) {
if (System.currentTimeMillis() - time == 1100) {
i++;
log.info("任务1执行中,模拟耗时步骤[{}]",i);
if (threadNow.isInterrupted()) {
log.error("任务1被中断");
throw new RuntimeException("任务1超时");
}
time = System.currentTimeMillis();
}
}
log.info("任务1结束...模拟条件用");
return null;
}), "任务1"));
for (WarpFeature<Object> future : futures) {
try {
future.f.get(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.error("InterruptedException{}", e.getMessage(), e);
} catch (ExecutionException e) {
log.error("ExecutionException{}", e.getMessage(), e);
} catch (TimeoutException e) {
future.f.cancel(true);
log.info("{}超时了", future.name);
}
}
log.info("下班啦");
try {
TimeUnit.SECONDS.sleep(300l);
} catch (InterruptedException e) {
e.printStackTrace();
}
}