Java Executor服务关闭现在,它是如何工作的
根据doc的方法Java Executor服务关闭现在,它是如何工作的,java,concurrency,executorservice,Java,Concurrency,Executorservice,根据doc的方法立即关闭(执行服务) 我有以下代码: public static void main(String[] args) throws InterruptedException { ExecutorService service = Executors.newSingleThreadExecutor(r -> { final Thread thread = new Thread(r); thread.setDaemo
立即关闭
(执行服务)
我有以下代码:
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newSingleThreadExecutor(r -> {
final Thread thread = new Thread(r);
thread.setDaemon(false);
return thread;
});
service.submit(() -> {
while (true) {
Thread.sleep(1000);
System.out.println("Done: " + Thread.currentThread().isInterrupted());
}
});
Thread.sleep(3000);
service.shutdownNow();
}
这是输出:
Done: false
Done: false
两次循环后,停止执行。
关机如何中断我的工作,我只有无限循环,没有检查Thread.currentThread.isInterrupted()代码>
在我看来,shutdownNow
只调用工作线程的中断方法,这是一种内部机制,但如果您像下面这样添加try-nad-catch,您将从sleep方法中抛出InterruptedException(因为线程已经被shutdown方法中断),因此shutdown方法确实会改变线程状态
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newSingleThreadExecutor(r -> {
final Thread thread = new Thread(r);
thread.setDaemon(false);
return thread;
});
service.submit(() -> {
try {
while (true) {
Thread.sleep(1000);
System.out.println("Done: " + Thread.currentThread().isInterrupted());
}
} catch (Exception e1) {
e1.printStackTrace();
}
});
Thread.sleep(3000);
service.shutdownNow();
}
Thread.sleep()
检查.isInterrupted()
并在中断时抛出中断异常。您的lambda隐式地抛出InterruptedException
,因此当执行器关闭时,它永远不会到达System.out.println
。您可以浏览查看这是如何发生的。在submit
返回的Future
上调用cancel
如何
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newSingleThreadExecutor(r -> {
final Thread thread = new Thread(r);
thread.setDaemon(false);
return thread;
});
service.submit(() -> {
try {
while (true) {
Thread.sleep(1000);
System.out.println("Done: " + Thread.currentThread().isInterrupted());
}
} catch (Exception e1) {
e1.printStackTrace();
}
});
Thread.sleep(3000);
service.shutdownNow();
}