Junior — Middle
How to organize synchronization so that one thread waits for the completion of two other threads?
sobes.tech AI
Answer from AI
In Java, to have one thread wait for the completion of two others, you can use the join() method on threads.
Example:
Thread t1 = new Thread(() -> {
// code for the first thread
});
Thread t2 = new Thread(() -> {
// code for the second thread
});
t1.start();
t2.start();
// Main thread waits for t1 and t2 to finish
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// After this, you can continue working, knowing both threads have finished
You can also use more advanced synchronization tools, such as CountDownLatch from java.util.concurrent:
CountDownLatch latch = new CountDownLatch(2);
Thread t1 = new Thread(() -> {
// work
latch.countDown();
});
Thread t2 = new Thread(() -> {
// work
latch.countDown();
});
t1.start();
t2.start();
// Wait until both threads call countDown()
latch.await();
// Continue working
Both methods allow organizing the waiting for multiple threads to complete.