(想在网上找一个wait和notify的代码例子,发现有个缺陷,如果没有中间睡眠的5秒,那么线程1完全不需要notify,因为线程2走不到wait。我做了改进,可以让两个线程进行来回唤醒。)正确代码在下面自取。
为保持线程可见,应该在count上加上volatile。只要看懂下面的代码,再去百度一下wait和sleep的区别,就应该就不用去背了。我理解,java八股文就应该理解性去记忆。
package test;
public class GreatNickName {
private volatile int count = 0;
private Object lock = new Object(); // 锁对象
public synchronized void increment() throws InterruptedException {
while (count == 0) { // 当count为0时,等待被通知
wait();
}
count++;
try {
Thread.sleep(5000); // 模拟任务执行时间
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " incremented to " + count);
notify(); // 唤醒可能正在等待的线程
}
public synchronized void decrement() throws InterruptedException {
while (count!= 0) { // 当count大于0时,等待变为0
wait();
}
count--;
try {
Thread.sleep(5000); // 模拟任务执行时间
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " decremented to " + count);
//notify(); // 唤醒其他线程
}
public static void main(String[] args) {
GreatNickName resource = new GreatNickName();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 3; i++) {
try {
resource.increment();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
Thread.sleep(100); // 模拟任务执行时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 3; i++) {
try {
resource.decrement();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
Thread.sleep(100); // 模拟任务执行时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
测试wait和notify
最新推荐文章于 2025-12-15 08:57:28 发布
2069

被折叠的 条评论
为什么被折叠?



