0

Following situation: Thread A starts Thread B and should wait until Thread B has done its job. Thread B could start a new Thread C. If it is the case Thread A should wait for Thread B and Thread C.

I could implement it using two CountDownLatch, but I'm wondering if there is a better solution. I have looked to CyclicBarrier and Phaser, but I don't think they are appropriate in my case.

Neo
  • 1,337
  • 4
  • 21
  • 50
  • 1
    Stupid questions: it seems you intend to do two, or three things more almost in sequence. Why using three threads then? Why not have one thread that does that bit of A, runs B, maybe C, waits for C, does the rest of A? – GhostCat May 15 '19 at 13:41
  • To do what you're asking, I'd probably just use [`Object::wait`](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait--) and [`Object::notify`](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#notify--). Have Thread A `wait` until Thread B `notify`~ies it. If Thread B starts Thread C have it do the same. Not that I'm saying this seems like a sane use of threads though. – BeUndead May 15 '19 at 14:06

1 Answers1

0

You can use Thread.join

final Thread c = new Thread(() -> {doSomethingInThreadC()});
c.start();
final Thread b = new Thread(() -> {
  doSomethingInThreadB_I();
  c.join(); // wait until thread C is completed
  doSomethingInThreadB_II();
});
b.start();
Thread a = new Thread(() -> {
  doSomethingInThreadA_I();
  b.join(); // wait until thread B is completed
  doSomethingInThreadA_II();
});
s.start();

However, this approach has some limitation - it waits until thread is stopped (not until some action is completed). If threads B and C are pooled threads then these will never stop.

If you are looking for job done then use wait/notify

Alexander Pavlov
  • 2,264
  • 18
  • 25