java - 程序结束时关闭java执行器服务

标签 java multithreading executorservice

考虑以下代码:

public class ExchangeDataSimulatorStartup {

    public static ExecutorService executorService = Executors
            .newFixedThreadPool(Integer.parseInt(10);

public static void pullData() {


    boolean shutdown = false;

    while (!shutdown) {

        // create a list to hold the Future object associated with Callable
        List<Future<String>> futureList = new ArrayList<Future<String>>();

        while (stockSymbolsListItr.hasNext()) {
            PullStocksData pullStocksData = new PullStocksData(
                    stockSymbolsListItr.next());

            // submit Callable tasks to be executed by thread pool
            Future<String> future = executorService.submit(pullStocksData);

            // add Future to the list, we can get return value using Future
            futureList.add(future);
        }

    }
}

我需要执行程序服务在应用程序收到关闭信号时关闭。否则执行者应该继续运行。所以我在另一篇文章中看到了以下实现,它说我应该在我的主要功能中添加类似以下代码的内容:

try {

    // We will now start our ExchangeDataSimulator
        ExchangeDataSimulatorStartup.pullData();

 } catch (Exception ex) {

      // do some logging

 } finally {

   executorService.shutdown();

}

我相信上面的代码可以正常工作。它(在 main 方法的 finally block 中关闭执行程序)是正确的方法吗?对此有更好的方法吗?

最佳答案

通常我想给任务一个完成的机会,但时间不会太长。方法见下图:

/**
 * Shutdown the given executor service and wait for tasks to finish.
 * If tasks do not finish within the given time-out, the executor service is forcibly closed
 * (running tasks are interrupted) and tasks that never commenced execution are returned.  
 * @param es the executor service to shutdown
 * @param timeoutSeconds the maximum time in seconds to wait.
 * @return null on normal shutdown, else a list of tasks that never commenced execution
 */
public static List<Runnable> shutdown(ExecutorService es, int timeoutSeconds) {

    es.shutdown();
    if (timeoutSeconds > 0) {
        try {
            es.awaitTermination(timeoutSeconds, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.warn("Waiting for executor service tasks completion interrupted.", e);
        }
    }
    return (es.isTerminated() ? null : es.shutdownNow());
}

关于java - 程序结束时关闭java执行器服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23151988/

相关文章:

java - 如何在 Try Catch 猜猜游戏中继续循环

java - Cometd 服务器广播 channel 自动删除

multithreading - 在 TThread 上创建 MainForm

java - 如何从 future 对象中查看执行了哪个线程(名称)

java - 可重用Executor、ServiceExecutor等接口(interface)的目的

java - ORA-12519, TNS :no appropriate service handler found while inserting into Oracle Database with X threads

java - 在方法/函数中使用类变量会创建对源的引用而不是重复它?

java - 来自数组的 boolean 值 - java 中的函数,从命令行输入

java - 2D 游戏 - 渲染时或在另一个线程中计算?

.net - 分析线程同步锁争用