![](/img/trans.png)
[英]Communication between java threads: stopping all threads when one finishes its task
[英]java threads: stopping all threads when one finishes its task
我用线程池创建了两个线程,如果其中一个完成了,则需要停止其他线程。 我怎样才能实现?
我的想法是使用AtomicBoolean或者CountDownLatch来实现。我的代码如下:
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
public class Test {
public static void main(String[] args) {
//Thread Pool
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
ExecutorService executorService = new ThreadPoolExecutor(6, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
AtomicBoolean atomicBool = new AtomicBoolean(false);
System.out.println("start");
for (int i = 0; i < 2; i++) {
//If any threads are executed, all threads end immediately
if (atomicBool.get() == true) {
executorService.shutdownNow();
}
executorService.execute(() -> {
System.out.println(Thread.currentThread().getName());
//do something
//....
atomicBool.set(true);
});
}
if (atomicBool.get() == true) {
executorService.shutdownNow();
}
System.out.println("end");
}}
但是两个线程都完成了,结果如下:
start
end
demo-pool-0
demo-pool-1
我应该怎么办?
除了使用AtomicBoolean
,您还可以使用CountDownLatch
的实例并将其传递给每个线程以等待达到倒计时值(在您的示例中,锁存器将初始化为 1)。 主线程在锁存器上调用await()
并将阻塞直到至少一个线程调用countDown()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.