2

Let us assume we have a method:

public class DoStuff implements Runnable {
    public void run()
    {
        A();
        B();
        C();
    }
}

Is there a simple way to create n threads that will run all A(), then all B(), then all C()?

I know that I can do something like:

    ExecutorService app = Executors.newFixedThreadPool(threadCount);

    //create A class and run A();

    app.shutdown();

    app.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

For A() then B() then C(), but I want something like the following:

public class DoStuff implements Runnable {
    public void run()
    {
        A();
        //wait all A to finish;
        B();
        //wait all B to finish;
        C();
    }
}

Using the same threads all the time.

Clark Kent
  • 1,178
  • 1
  • 12
  • 26
Nahum
  • 6,959
  • 12
  • 48
  • 69
  • 3
    Have a look at `CountDownLatch` https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html – Qwerky May 28 '15 at 10:47
  • 1
    @Qwerky - A `CountDownLatch` cannot be *re-initialized*. Whereas a `CyclicBarrier` can be. So the OP will ahve to call `await()` after each method call to make the *current thread wait* and then initialize the `CyclicBarrier count` again and then call `await()` for `B` and so on – TheLostMind May 28 '15 at 10:52
  • In addition to the actual answers to your question, please consider SRP ( http://www.oodesign.com/single-responsibility-principle.html ) as well. A method should be doing **one** thing. Not two, three or n. Meaning: probably your threads should not be executing a run() with "A; B; C;" ... but run() with either "A", or "B", or "C". – GhostCat May 28 '15 at 10:52
  • @TheLostMind I think I would have two `CountDownLatch` instances, one inbetween A and B, and another in between B and C. – Qwerky May 28 '15 at 10:56
  • @Qwerky - That would work as well..:) – TheLostMind May 28 '15 at 11:07
  • @Jägermeister, the sequence A(); B(); C(); might _be_ one thing when described at a higher level of abstraction. – Solomon Slow May 28 '15 at 16:03

2 Answers2

4

You are looking for CyclicBarrier

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html

Christopher Oezbek
  • 23,994
  • 6
  • 61
  • 85
  • Relevant: http://stackoverflow.com/questions/4168772/java-concurrency-countdown-latch-vs-cyclic-barrier – Qwerky May 28 '15 at 10:50
-1

you need to make A, B and C as threads and you need to join them. Join A with B and B with C.

In this way you are making B thread to wait until A's job is done and C thread to wait until B's job is done.

Pavan Kumar K
  • 1,360
  • 9
  • 11