相关疑难解决方法(0)

如何等待ThreadPoolExecutor完成

我的问题:如何在a上执行一堆线程对象ThreadPoolExecutor并等待它们全部完成然后再继续?

我是ThreadPoolExecutor的新手.因此,此代码是一项测试,以了解它是如何工作的.现在我甚至没有填充BlockingQueue对象,因为我不知道如何启动队列而不用execute()另一个调用RunnableObject.无论如何,现在我只是打电话,awaitTermination()但我想我仍然缺少一些东西.任何提示都会很棒!谢谢.

public void testThreadPoolExecutor() throws InterruptedException {
  int limit = 20;
  BlockingQueue q = new ArrayBlockingQueue(limit);
  ThreadPoolExecutor ex = new ThreadPoolExecutor(limit, limit, 20, TimeUnit.SECONDS, q);
  for (int i = 0; i < limit; i++) {
    ex.execute(new RunnableObject(i + 1));
  }
  ex.awaitTermination(2, TimeUnit.SECONDS);
  System.out.println("finished");
}
Run Code Online (Sandbox Code Playgroud)

RunnableObject类:

package playground;

public class RunnableObject implements Runnable {

  private final int id;

  public RunnableObject(int id) {
    this.id = id;
  }

  @Override
  public void …
Run Code Online (Sandbox Code Playgroud)

java multithreading threadpool

30
推荐指数
2
解决办法
4万
查看次数

标签 统计

java ×1

multithreading ×1

threadpool ×1