段小言
段小言

Reputation: 22

java threads: stopping all threads when one finishes its task

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?

Upvotes: 0

Views: 72

Answers (1)

Josh
Josh

Reputation: 500

Instead of using the AtomicBoolean, you can use an instance of CountDownLatch and pass it to each thread to wait until the countdown value has been reached (in your example the latch would be initialized with 1). The main thread calls await() on the latch and that will block until at least one thread has called countDown().

https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/concurrent/CountDownLatch.html

Upvotes: 1

Related Questions