代码之家  ›  专栏  ›  技术社区  ›  walters

ScheduledExecutorService启动停止多次

  •  15
  • walters  · 技术社区  · 15 年前

    我在用 ScheduledExecutorService ,在我叫它之后 shutdown 方法,我无法在其上计划可运行。打电话 scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS) 之后 shutdown() 抛出java.util.concurrent.RejectedExecutionException。之后是否有其他方法运行新任务 关闭() 被召唤 ScheduledExecutorService计划 ?

    3 回复  |  直到 15 年前
        1
  •  42
  •   Alex Objelean    14 年前

    您可以重用调度程序,但不应该关闭它。相反,取消调用scheduleAtFixedRate方法时可以获得的正在运行的线程。前任:

    //get reference to the future
    Future<?> future = service.scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS)
    //cancel instead of shutdown
    future.cancel(true);
    //schedule again (reuse)
    future = service.scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS)
    //shutdown when you don't need to reuse the service anymore
    service.shutdown()
    
        2
  •  6
  •   Peter Knego    15 年前

    的javadocs shutdown() 说:

    Initiates an orderly shutdown in which previously submitted tasks are executed,
    but no new tasks will be accepted.
    

    所以,你不能打电话 shutdow() 然后安排新任务。

        3
  •  2
  •   Kent Murra    14 年前

    你不能让你的执行者在关闭后接受新任务。更相关的问题是,为什么你首先需要关闭它?您创建的执行器应该在应用程序或子系统的整个生命周期内重复使用。