Reputation: 585
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
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
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
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