![](/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.