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

来源:互联网 发布:java错误调试 编辑:程序博客网 时间:2024/04/28 12:46
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 0
原创粉丝点击