线程通信,生产者与消费者

public class ThreadTest {
    public static void main(String[] args) {
        //需求:3个生产者线程,负责生产包子,每个线程只能生产一个包子放在桌子上
        //     2个消费者线程负责吃包子,每人每次只能从桌子上哪一个包子吃
        Desk desk = new Desk();
        //创建三个生产者线程
        new Thread(() -> {
            while (true) {
                desk.put();
            }
        },"厨师1").start();

        new Thread(() -> {
            while (true) {
                desk.put();
            }
        },"厨师2").start();

        new Thread(() -> {
            while (true) {
                desk.put();
            }
        },"厨师3").start();

        //创建两个消费者线程

        new Thread(() -> {
            while (true) {
                desk.get();
            }
        },"吃货1").start();

        new Thread(() -> {
            while (true) {
                desk.get();
            }
        },"吃货2").start();
    }
}
import java.util.ArrayList;
import java.util.List;

public class Desk {
    private List<String> list = new ArrayList();

    public synchronized void put() {
        try {
            String name = Thread.currentThread().getName();
            if(list.size()==0){
                list.add(name+"做的包子");
                System.out.println(name+"做了一个包子");
                Thread.sleep(2000);

                //等待自己,唤醒别人,用当前对象调用 wait(),notify()方法
                this.notifyAll();
                this.wait();
            }else {
                //有包子了,不做了
                this.notifyAll();
                this.wait();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public synchronized void get() {
        try {
            String name = Thread.currentThread().getName();
            if(list.size()==1) {
                System.out.println(name + list.get(0));
                list.clear();
                this.notifyAll();
                this.wait();
            }else{
                //没有包子
                this.notifyAll();
                this.wait();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值