如何覆盖executorService shutdown方法

时间:2016-10-15 22:17:42

标签: java multithreading threadpool executorservice shutdown

我正在创建自己的线程池和将来可以执行可调用接口并行的对象。 Executor提供shutdown方法来阻止所有工作线程运行。如果我正在创建一个如下所示的线程池,我应该如何在所有线程完成执行后实现shutdown方法停止?

我的自定义线程池看起来像this

class MyThreadPool implements java.util.concurrent.Executor 
{
    private final java.util.concurrent.BlockingQueue<Callable> queue;

    public MyThreadPool(int numThreads) {
        queue = new java.util.concurrent.LinkedBlockingQueue<>();
        for (int i=0 ; i<numThreads ; i++) {
            new Thread(new Runnable(){
                @Override
                public void run() {
                    while(true) {
                        queue.take().call();
                    }
                }
            }).start();
        }
    }

  @Override
  public <T> Future<T> submit(Callable<T> callable) {
    FutureTask<T> future = new FutureTask(callable);
    queue.put(future);
    return future;
  }

  public void shutdown(){ }
}

我想不出一种方法来保持线程列表,然后检查它们是否空闲?

1 个答案:

答案 0 :(得分:1)

你绝对应该保留对你正在创建的主题的引用。例如,设置类型为threads的字段List<Thread>,并在构造函数中将线程添加到此列表中。

之后,您可以在Thread#join()的帮助下实施shutdown()

public void shutdown() {
    for (Thread t : threads) {
        try {
            t.join();
        } catch (InterruptedException e) { /* NOP */ }
    }
}

请勿忘记将while (true)替换为适当的条件(您在shutdown()中切换),并考虑使用BlockingQueue#poll(long, TimeUnit)而不是take()

编辑:类似于:

public class MyThreadPool implements Executor {

    private List<Thread> threads = new ArrayList<>();
    private BlockingDeque<Callable> tasks = new LinkedBlockingDeque<>();
    private volatile boolean running = true;

    public MyThreadPool(int numberOfThreads) {
        for (int i = 0; i < numberOfThreads; i++) {
            Thread t = new Thread(() -> {
                while (running) {
                    try {
                        Callable c = tasks.poll(5L, TimeUnit.SECONDS);
                        if (c != null) {
                            c.call();
                        }
                    } catch (Exception e) { /* NOP */ }
                }
            });
            t.start();
            threads.add(t);
        }
    }

    public void shutdown() {
        running = false;
        for (Thread t : threads) {
            try {
                t.join();
            } catch (InterruptedException e) { /* NOP */ }
        }
    }

    // ...

}