我正在创建自己的线程池和将来可以执行可调用接口并行的对象. 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(){ }
}
我想不出一种方法来保持线程列表,然后检查它们是否空闲?
解决方法:
你肯定应该持有你正在创建的线程的引用.例如,设置List< Thread>类型的字段线程.并从构造函数中将线程添加到此列表中.
之后,您可以在Thread#join()
的帮助下实现shutdown():
public void shutdown() {
for (Thread t : threads) {
try {
t.join();
} catch (InterruptedException e) { /* NOP */ }
}
}
不要忘记用适当的条件(在shutdown()中切换)替换while(true)并考虑使用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 */ }
}
}
// ...
}