多线程生产者与消费者问题

博客介绍了Java中Object类的相关方法,包括wait()系列方法,可使当前线程等待被唤醒,以及notify()和notifyAll()方法,分别用于唤醒单个线程和所有等待此对象监视器的线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Object类
方法:
wait() //导致当前线程等待它被唤醒,通常是 通知或 中断 。
wait​(long timeoutMillis)
wait​(long timeoutMillis, int nanos)
notify() //唤醒正在此对象监视器上等待的单个线程。
notifyAll() //唤醒等待此对象监视器的所有线程。

public class Demo3 {
    public static void main(String[] args) {
        Food f = new Food();
        Cooker c = new Cooker(f);
        c.start();
        Waiter w = new Waiter(f);
        w.start();
    }

    static class Cooker extends Thread{
        private Food f;
        public Cooker(Food f){
            this.f = f;
        }
        @Override
        public void run() {
            for (int i=0;i<100;i++){
                if(i%2==0){
                    f.set("青椒肉丝","香辣");
                }else{
                    f.set("土豆泥","咸香");
                }
            }
        }
    }

    static class Waiter extends Thread{
        private Food f;
        public Waiter(Food f){
            this.f = f;
        }

        @Override
        public void run() {
            for(int i=0;i<100;i++){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                f.get();
            }
        }
    }

    static class Food{
        private String name;
        private String taste;

        //true表示可以生产
        private boolean flag = true;
        //同步方法
        public synchronized void set(String name,String taste){
            if(flag==true){
                this.name = name;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.taste = taste;
                flag=false;
                //唤醒所有线程
                this.notifyAll();
                try {
                    //使Cooker线程睡眠
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        //同步方法
        public synchronized void get(){
            if(!flag){
                System.out.println("服务员端走的菜名:"+name+",味道:"+taste);
                flag=true;
                //唤醒所有线程
                this.notifyAll();
                try {
                    //使Waiter线程睡眠
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值