//ProducerConsumer2.javapublic class ProducerConsumer2{public static void main(String args[]){PiggyBank1 pb=new PiggyBank1();Mother1 m=new Mother1(pb);Son1 s=new Son1(pb);m.setPriority(6); //改变母亲线程的优先级为6s.setPriority(2); //改变儿子线程的优先级为2s.start(); //先启动儿子线程m.start();}}class Mother1 extends Thread //母亲类,储钱罐是它的属性{PiggyBank1 pb;Mother1(PiggyBank1 pb){this.pb=pb;}public void run() //母亲的行为是向储钱罐中放入10元钱,共计5次{for (int i = 1; i <= 5; i++){pb.put(i);}}}class Son1 extends Thread //儿子类,储钱罐是它的属性{PiggyBank1 pb;Son1(PiggyBank1 pb){this.pb=pb;}public void run() //儿子的行为是从储钱罐中取钱,一次取10元,共计5次{for (int i = 1; i <= 5; i++){pb.get();}}}class PiggyBank1 //储钱罐类{private int number; //表示储钱罐中当前这张十元钱的编号private boolean empty=true; //表示储钱罐是否为空的布尔属性synchronized void get(){while(empty==true) //如果储钱罐中没有钱,则不能从中取钱{try{wait(); //线程进入等待池中}catch (InterruptedException e){}}empty=true;System.out.println("儿子从储钱罐中取第" + number+"个十元钱");notify(); //唤醒等待从储钱罐中取钱的线程}synchronized void put(int i){while(empty==false) //如果储钱罐中有钱,则不能再向其中放入钱{try{wait();}catch (InterruptedException e){}}number=i;empty=false;System.out.println("妈妈向储钱罐中放第" + i+"个十元钱");notify(); //唤醒等待向储钱罐中放入钱的线程}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。