Running groups of threads

40 views Asked by At

Lets say I have a few groups of threads in java which I want to implement in this way: at each point of time, only one group of threads can run, and the others should wait for their turn (cyclic).

How you would recommend to do so?

1

There are 1 answers

0
AudioBubble On BEST ANSWER

You can use a CyclicBarrier to prevent one group of threads from running while the other group is still progressing. You can release the next group using a CountDownLatch.

What you would do is wait for the group before the current to reset the cyclic barrier before continuing. The barrier would be reset after all the threads countDown the latch.

For example:

CyclicBarrier nextGroupContinue = new CyclicBarrier(1);
ExecutorService service = Executors.newCachedThreadPool();
final Runnable[][] groups = // init

try {
    for (Runnable[] group : groups) {
        int threads = group.length;
        final CountDownLatch reset = new CountDownLatch(threads);

        nextGroupContinue.await();
        for (final Runnable runnable : group) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    runnable.run();
                    reset.countDown();
                }
            });
        }

        reset.await();
        nextGroupContinue.reset();
    }
} catch (InterruptedException | BrokenBarrierException e) {
    e.printStackTrace();
}

service.shutdownNow();