Java_Jack
Java_Jack

Reputation: 585

Without using Thread.Join() , how can i achive same functionality

We are having two thread J1 and J2. How can we make sure that thread J2 run only after J1 has completed its execution without using join() method.

Upvotes: 4

Views: 211

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136042

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

public class Test1 {

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

note the magic - something wakes up t.wait() - this is because JVM notifies the Thread object when it terminates

Upvotes: 1

VKPRO
VKPRO

Reputation: 159

Another way to achieve this is using Locks

   class X {
         private final ReentrantLock lock = new ReentrantLock();
          // ...

         public void m() { 
           lock.lock();  // block until condition holds
           try {
              // ... method body
          } finally {
               lock.unlock()
          }
        }
   } 

Upvotes: 0

goblinjuice
goblinjuice

Reputation: 3214

Simple, use a CountDownLatch.

Initialize the CountDownLatch to 1 in the main(). Pass it to both J1 and J2. J2 simply waits for the Latch to become 0 using await(). J2 sets it to 0 once done using countDown(), signalling J1 to start.

Upvotes: 4

Related Questions