如何停止ScheduledExecutorService? [英] How to stop a ScheduledExecutorService?
问题描述
程序在九次打印后完成:
The program finishes after nine prints:
class BeeperControl {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void beep() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
}
};
final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(
beeper, 1, 1, SECONDS);
scheduler.schedule(new Runnable() {
public void run() {
beeperHandle.cancel(true);
}
}, 1 * 9, SECONDS);
}
public static void main(String[] args) {
BeeperControl bc = new BeeperControl();
bc.beep();
}
}
如何停止进程(即eclipse中的java进程)例如)因为它在9秒内没有停止时间?
How to stop a process (i.e. java process in eclipse for example) because it does not stop after a time limit in 9 seconds?
推荐答案
你遇到的问题是调度程序保持不变取消蜂鸣声任务后的实时线程。
The issue you have is that the scheduler keeps a live thread around after you have cancelled the beep task.
如果有一个实时非守护程序线程,则JVM保持活动状态。
If there is a live non-daemon thread, the JVM stays alive.
它保留这个线程的原因是你告诉它在这一行中这样做:
The reason that it keeps this thread around is that you have told it to do so in this line:
private final ScheduledExecutorService scheduler
= Executors.newScheduledThreadPool(1);
请注意 newScheduledThreadPool(int corePoolSize)
:
corePoolSize
- 要保留在池中的线程数,甚至如果他们闲着。
corePoolSize
- the number of threads to keep in the pool, even if they are idle.
那么,你有两种方法可以让JVM终止:
So, you have two possible ways to cause the JVM to terminate:
-
将
0
传递给newScheduledThreadPool
而不是1 。调度程序不会保留活动线程,JVM将终止。
Pass
0
tonewScheduledThreadPool
instead of 1. The scheduler will not keep a live thread, and the JVM will terminate.
关闭调度程序。无论如何,您应该这样做以释放其资源。因此,将匿名 Runnable
中的运行
更改为:
Shut down the scheduler. You are supposed to do so anyway to release its resources. So change the run
in your anonymous Runnable
to:
public void run() {
beeperHandle.cancel(true);
scheduler.shutdown();
}
(事实上,那里不需要取消
- shutdown
将在下一次嘟嘟完成后立即生效。)
(In fact, you don't need the cancel
there - the shutdown
will take effect as soon as the next "beep" is completed.)
这篇关于如何停止ScheduledExecutorService?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!