多线程同步问题:Java中的wait/notify用法示例
在Java中,wait和notify是用于线程同步的两个关键方法。当一个线程需要等待某个条件满足时,会调用wait();而另一个线程在条件满足后,会调用notify()或notifyAll()。
以下是一个简单的示例,展示了wait/notify的使用:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
notifyAll(); // 当count大于0时唤醒所有等待的线程
}
public synchronized void decrement() {
if (count > 0) {
count--;
if (count == 0) { // 如果count为0,表示计数器为空
notifyAll(); // 唤醒所有等待的线程
}
}
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
// 创建两个线程并开始执行
Thread thread1 = new Thread(() -> {
while (true) { // 无限循环,直到被唤醒
try {
// 等待计数器不为空(即counter.increment()已经调用)
if (!counter.decrement()) {
break; // 当count为0时跳出循环
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}));
Thread thread2 = new Thread(() -> {
while (true) { // 无限循环,直到被唤醒
try {
// 等待计数器不为空(即counter.increment()已经调用)
if (!counter.increment()) {
break; // 当count大于0时跳出循环
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}));
thread1.start(); // 启动thread1
thread2.start(); // 启动thread2
// 当计数器为空(即counter.increment()未调用)时,会唤醒所有等待的线程
// 这里通过检查count是否为0来实现这个逻辑
}
}
在这个示例中,我们创建了一个Counter类,用于维护一个计数器。然后我们创建了两个线程thread1和thread2,它们在无限循环中等待被唤醒。最后当计数器为空时,会唤醒所有等待的线程。
还没有评论,来说两句吧...