我正在使用向上/向下计数锁存器来将程序限制为 6 个线程,它可以工作,但我真正想要的是始终运行 6 个线程。这样当一个线程死亡时,另一个线程就会启动。通过下面的实现,每当超时到期时,它一次只会创建 6 个新线程。
关于如何构造我的循环来完成此任务有什么建议吗?
int numThreads = 6;
CountUpDownLatch threadCounter = new CountUpDownLatch();
for(int t = 1; t <= numThreads; t++) {
while(list.hasNext()) {
new Thread(new ThreadController("processData",list.next())).start();
threadCounter.countUp();
}
try {
threadCounter.await(5, TimeUnit.MINUTES);
} catch (InterruptedException e) { e.printStackTrace(); }
}
最佳答案
使用包含 6 个线程的执行器服务,如下所示,
ExecutorService exec = Executors.newFixedThreadPool(6);
for (int i = 0; i < 10; i++) {
exec.submit(() -> System.out.println("Hello"));
}
exec.shutdown();
您可以将 Runnable
或 Callable
传递给 ExecutorService
的 submit
方法。在这里,我将 lambda 函数作为 Runnable
传递,该函数从 Java8 开始有效。根据您的情况,您可以这样做,
exec.submit(new ThreadController("processData",list.next()));
关于java - 有没有比 Await 更好的使用 CountUpDownLatch 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52631293/