How does Condition behave in multithreaded code?

In multithreaded programming, conditions are crucial for managing how threads interact, particularly when one thread needs to wait for a signal from another thread before proceeding. The Condition interface in Java allows threads to efficiently wait until they are signaled to continue execution, providing a way to manage thread coordination.

Conditions are typically used in conjunction with locks. A thread can acquire a lock and then call the await() method on a Condition object to release the lock and wait for a condition to be met. When another thread signals this condition using signal() or signalAll(), the waiting thread will be awakened and attempt to reacquire the lock.

Here's an example demonstrating how to use Condition in Java:

import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ConditionExample { private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private boolean conditionMet = false; public void producer() { lock.lock(); try { // Simulate some work with sleep Thread.sleep(1000); conditionMet = true; condition.signal(); // Signal the waiting consumer } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { lock.unlock(); } } public void consumer() { lock.lock(); try { while (!conditionMet) { condition.await(); // Wait until signaled } // Proceed knowing the condition is met } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { lock.unlock(); } } }

multithreading java condition thread coordination await signal