How do you use Condition with a simple code example?

In Java, the `Condition` interface is used in conjunction with `Lock` to achieve thread synchronization. It allows one or more threads to wait until they are signaled by another thread. This is particularly useful in situations where threads must wait for specific conditions to be met before they can proceed. Below is a simple example demonstrating the use of `Condition` to control thread execution.

import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ConditionExample { private static final Lock lock = new ReentrantLock(); private static final Condition condition = lock.newCondition(); private static boolean isReady = false; public static void main(String[] args) { Thread producer = new Thread(() -> { try { lock.lock(); isReady = true; condition.signal(); } finally { lock.unlock(); } }); Thread consumer = new Thread(() -> { try { lock.lock(); while (!isReady) { condition.await(); } System.out.println("Condition met, proceeding with consumer."); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { lock.unlock(); } }); consumer.start(); producer.start(); } }

Condition Java Thread Synchronization Lock ReentrantLock