package test1;
/**
* 虚假唤醒
*
* 为什么 if会出现虚假唤醒 -> 因为if只会执行一次,执行完会接着向下执行if()外边的
* 而while不会,直到条件满足才会向下执行while()外边的
*
*/
public class main {
public static void main(String[] args) {
PC1 pc1 = new PC1();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
pc1.producer();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "A").start();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
pc1.consumer();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "A").start();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
pc1.producer();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "B").start();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
pc1.consumer();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "B").start();
}
}
/**
* producer
* consumer
*
* @author Sage
* @date 2021/10/19
*/
class PC1{
private int goods = 0;
/**
* 生产商
*/
public synchronized void producer() throws InterruptedException {
while (goods != 0) {
this.wait();
}
System.out.println(Thread.currentThread().getName() + "=>" + "生产了一个货物");
goods++;
this.notifyAll();
}
/**
* 消费者
*/
public synchronized void consumer() throws InterruptedException {
while (goods == 0) {
this.wait();
}
System.out.println(Thread.currentThread().getName() + "=>" + "消费了一个货物");
goods--;
this.notifyAll();
}
}
最后编辑:2021年10月19日
©著作权归作者所有
最新回复