Without using Thread.Join (), how can I achieve the same functionality

We have two threads J1 and J2. How can we make sure that thread J2 starts only after J1 has completed execution, without using the join() method.

+4
source share
3 answers

Simple, use CountDownLatch .

Initialize CountDownLatch to 1 in main() . Pass it on to both J1 and J2. J2 just waits for the latch to become 0 using await() . J2 sets it to 0, once executed using countDown() , start J1 to start.

+4
source

I think this is very close to what Thread.join does.

 public class Test1 { public static void main(String[] args) throws Exception { Thread t = new Thread(); synchronized (t) { t.start(); while (t.isAlive()) { t.wait(); } } } } 

Pay attention to the magic - something wakes up t.wait () - this is because the JVM notifies the Thread object when it completes

+1
source

Another way to achieve this is to use Locks.

  class X { private final ReentrantLock lock = new ReentrantLock(); // ... public void m() { lock.lock(); // block until condition holds try { // ... method body } finally { lock.unlock() } } } 
0
source

Source: https://habr.com/ru/post/1480341/


All Articles