01蚂蚁-并发编程-并发编程之多线程基础——5.简单的生产者和消费者(先写一部分简单的后面写复杂的)

1.最简单的生产者消费者模式。

  1. wait :让线程等待,但是它会释放锁的资源。
  2. notify:唤醒当前对象锁池被等待的线程。
    注意:一定要在synchronized 进行执行,持有同一把锁

现在是生产者生产一个消费一个。生产完就等待,读操作,读完就写

package thread_day05;

class Res{
    public String name;
    public String sex;
    //为true 可读不可写,为false可写不可读
    public boolean flag = false;
}

//生产者线程
class InThread extends Thread{
    public Res res;
    public InThread(Res res){
        this.res = res;
    }
    @Override
    public void run() {
        int count = 0;
        while(true){
            synchronized (res) {
                if(res.flag){  //如果为true可读不可写,写等待
                    try {
                        res.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (count == 0) {
                    res.name = "小红";
                    res.sex = "女";
                } else {
                    res.name = "小军";
                    res.sex = "男";
                }
                count = (count + 1) % 2;
                res.flag=true;//标记当前线程为等待
                res.notify(); //唤醒写线程
            }
        }
    }
}

class OutThread extends Thread{
    public Res res;
    public OutThread(Res res){
        this.res = res;
    }
    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                if(!res.flag){  //如果为false 就是可写不可读
                    try {
                        res.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    System.out.println(res.name + "," + res.sex);
                    res.flag = false; //读完了就改为false 改为可写不可读
                    res.notify();   //唤醒写线程去写
                }
            }
        }
    }
}

public class Test0001 {
    public static void main(String[] args) {
        Res res = new Res();
        InThread inThread = new InThread(res);
        OutThread outThread = new OutThread(res);
        inThread.start();
        outThread.start();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值