Java 如何停止 ScheduledExecutorService?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34202701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:25:01  来源:igfitidea点击:

How to stop a ScheduledExecutorService?

javaexecutorservice

提问by ferro

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();
    }
}

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?

如何停止一个进程(例如 eclipse 中的 java 进程),因为它在 9 秒的时间限制后没有停止?

采纳答案by RealSkeptic

The issue you have is that the scheduler keeps a live thread around after you have cancelled the beep task.

您遇到的问题是,在您取消哔声任务后,调度程序会保留一个实时线程。

If there is a live non-daemon thread, the JVM stays alive.

如果存在活动的非守护线程,则 JVM 会保持活动状态。

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);

Note the documentation of newScheduledThreadPool(int corePoolSize):

请注意以下文档newScheduledThreadPool(int corePoolSize)

corePoolSize- the number of threads to keep in the pool, even if they are idle.

corePoolSize- 要保留在池中的线​​程数,即使它们处于空闲状态。

So, you have two possible ways to cause the JVM to terminate:

因此,您有两种可能的方法来导致 JVM 终止:

  1. Pass 0to newScheduledThreadPoolinstead of 1. The scheduler will not keep a live thread, and the JVM will terminate.

  2. Shut down the scheduler. You are supposed to do so anyway to release its resources. So change the runin your anonymous Runnableto:

    public void run() {
        beeperHandle.cancel(true);
        scheduler.shutdown();
    }
    
  1. 传递0newScheduledThreadPool而不是 1。调度程序不会保持活动线程,JVM 将终止。

  2. 关闭调度程序。无论如何,您都应该这样做以释放其资源。因此run,将匿名更改Runnable为:

    public void run() {
        beeperHandle.cancel(true);
        scheduler.shutdown();
    }
    

(In fact, you don't need the cancelthere - the shutdownwill take effect as soon as the next "beep" is completed.)

(实际上,您不需要cancel那里 -shutdown一旦下一个“哔”声完成,它将立即生效。)