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();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?