这是关于线程的一个问题
new Thread().start(); //线程的启动
this.notify();//唤醒线程
传统的生产者和消费者模式,wait(),notifyAll()的方式实现,但只适用与两个线程,如果存在两个以上的线程,会出现虚假唤醒的问题。
package com.xnizhi;
import java.util.Date;
/**
* @author LZP
* @create 2020/7/8
*/
public class PC {
public static void main(String[] args) {
Data data = new Data();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data.add();
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data.del();
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data.del();
}
}, "C").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data.del();
}
}, "D").start();
}
}
class Data {
int number = 0;
public synchronized void add() {
if(number != 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
number++;
System.out.println(Thread.currentThread().getName() + "是" + number);
this.notify(); //唤醒线程
}
public synchronized void del() {
if(number == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
number--;
System.out.println(Thread.currentThread().getName() + "是" + number);
this.notify();
}
}
当他是两个线程的时候是可以看到正常的代码的,但是当线程数大于两个的时候就会出现这样的效果.
这时候只需要将if换成while即可.