package com.hdu.juc;
public class PC {
public static void main(String[] args) {
Data data = new Data();
new Thread(()->{
for (int i = 0; i < 100; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(()->{
for (int i = 0; i < 100; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
class Data{
int num = 0;
public synchronized void increment() throws InterruptedException {
while(num!=0) this.wait();
num++;
System.out.println("increment:" + num);
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException {
while(num==0) this.wait();
num--;
System.out.println("decrement:" + num);
this.notifyAll();
}
}
- 注意wait方法应放在循环体中,因为存在虚假唤醒,当在循环体中,线程即使被虚假唤醒抢到锁也没有跳出循环,继续判断进入阻塞。如果是if条件,当线程被唤醒抢到锁便执行num++或num–操作。