有一个和尚负责做馒头,做好30个其它三个和尚就可以吃馒头, *当馒头吃完了,第一个和尚就再做30个馒头 生产消费

package ;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dell on 2017/5/4.
 * 有一个和尚负责做馒头,做好30个其它三个和尚就可以吃馒头,
 * 当馒头吃完了,第一个和尚就再做30个馒头  生产消费
 */
public class Test {
    public static List<String> datas=new ArrayList<>();
    public static void main(String[] args) {
        new HuFu().start();
        new ChiHuo("白眉和尚").start();
        new ChiHuo("酒鼻子和尚").start();
        new ChiHuo("花和尚").start();
    }
}
class HuFu extends Thread{

    @Override
    public void run() {
        while(true) {
            //做馒头和喊醒并休息
            synchronized ("b") {
                for (int i = 1; i <= 30; i++) {
                    Test.datas.add("第" + i + "个馒头");
                    System.out.println("已做好第" + i + "个馒头");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("馒头已做够,开始叫醒吃货们");
                "b".notifyAll();
            }
            //XXX.notifyAll()
            synchronized ("a"){
                try {
                    "a".wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
class ChiHuo extends Thread{
    private String name;

    public ChiHuo(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        //吃没了就唤醒火夫并休息
        while(true) {
            String s=null;
            synchronized ("b") {
                if(Test.datas.size()==0){
                    synchronized ("a"){
                        System.out.println(name+"发现没有馒头了,去叫醒火夫");
                        "a".notify();
                    }
                    try {
                        "b".wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    s = Test.datas.remove(0);
                    System.out.println(name + "吃掉了" + s);
                }
            }

            try {
                Thread.sleep((long) (Math.random() * 2000 + 1));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值