I created two threads with the thread pool, and if one of them is finished, the other threads need to be stopped. How can i achieve?
My idea is to use AtomicBoolean or CountDownLatch to achieve.My code is as follows:
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"); }}
But both threads are finished,The result is as follows:
start end demo-pool-0 demo-pool-1
what should I do?
https://stackoverflow.com/questions/67249021/java-threads-stopping-all-threads-when-one-finishes-its-task April 25, 2021 at 09:46AM
没有评论:
发表评论