传统消费者如何防止虚假唤醒????what?

这是关于线程的一个问题
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即可.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值