【发布时间】:2020-02-22 03:42:30
【问题描述】:
我创建了ExecutorService 并提交了一份工作。这项工作可能很耗时。所以我给了timeout 2 秒。如果执行时间超过 2 秒,我想杀死那个线程。
public void threadTest() {
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
executor.submit(() -> {
try {
String threadName = Thread.currentThread().getName();
Thread.sleep(7000);
System.out.println("process completed after 7 seconds");
} catch (Exception e) {
e.printStackTrace();
}
}).get(2, TimeUnit.SECONDS);
}catch (Exception e){
}
executor.shutdown();
}
public static void main(String[] args) throws Exception {
System.out.println("main start");
ThreadBreaker tb = new ThreadBreaker();
tb.threadTest();
System.out.println("main end");
}
输出
main start
main end
process completed after 7 seconds
函数threadTest 在 2 秒后退出,正如我所料。但是提交的作业继续运行。如果在给定的超时时间内无法完成,我想停止提交的任务。
【问题讨论】:
标签: java threadpool runnable executorservice threadpoolexecutor