我正在学习如何使用ExecutorService在Java中使用线程池,这是我正在研究的一个例子:
public class Example {
static class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s) {
this.command = s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Start. Command = " + command);
processCommand();
System.out.println(Thread.currentThread().getName() + " End.");
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return this.command;
}
}
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
// while (!executor.isTerminated()) {
// }
System.out.println("Finished all threads");
}
}
我有两个问题:
>如果我使用awaitTermination()或isTerminated(),我应该如何等待ExecutorService的终止(有人建议后者是一种错误的方法)?
> Runnables是否正确添加到执行程序中,还是应该将submit()与Future< T>一起使用?打回来?
它可能取决于上下文,所以你能解释(对于这两个问题)我应该何时使用所提到的每个解决方案.
解决方法:
几种方法来实现它:
(a)在(!executor.isTerminated())内部调用awaitTermination(long someTime,TimeUnit ….).
(b)将所有可调用的内容存储在Collection对象中并调用executor.invokeAll(….).这将等到所有任务由执行者服务完成.