import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
private static final int COUNT_THRESHOLD = 5;
private int count = 0;
private ReentrantLock lock = new ReentrantLock();
private Condition thresholdReachedCondition = lock.newCondition();
public void increment() {
lock.lock();
try {
count++;
System.out.println("Incremented: " + count);
if (count >= COUNT_THRESHOLD) {
thresholdReachedCondition.signalAll();
}
} finally {
lock.unlock();
}
}
public void waitForThreshold() throws InterruptedException {
lock.lock();
try {
while (count < COUNT_THRESHOLD) {
thresholdReachedCondition.await();
}
System.out.println("Threshold reached!");
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
Main demo = new Main();
Thread incrementThread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
demo.increment();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread waitThread = new Thread(() -> {
try {
demo.waitForThreshold();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
incrementThread.start();
waitThread.start();
try {
incrementThread.join();
waitThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
在上述示例中,我们创建了一个名为ConditionDemo的类来管理计数和等待阈值的逻辑。increment()方法用于递增计数,并在达到阈值时调用signalAll()来唤醒等待线程。waitForThreshold()方法用于等待阈值达到,并在达到时输出"Threshold reached!"。
在main()方法中,我们创建了一个递增线程和一个等待线程,并通过调用start()方法启动它们。然后使用join()方法等待两个线程完成。
运行示例,你会看到递增线程在每次递增时输出计数值,当计数达到阈值5时,等待线程被唤醒并输出"Threshold reached!"。
这个示例演示了如何使用Condition和ReentrantLock实现线程间的等待和唤醒机制。适当地使用lock()、unlock()、await()和signalAll()方法可以确保线程在正确的时机等待和唤醒,以实现同步和通信。
可见Java中的Condition类似C++中的C++ std::condition_variable,Java中的ReentrantLock类似于C++中的std::mutex。