//ProducerConsumer1.javapublic class ProducerConsumer1{public static void main(String args[]) {PiggyBank pb=new PiggyBank();Mother m=new Mother(pb);Son s=new Son(pb);m.start();s.start();}}class Mother extends Thread{ //母亲类,储钱罐是它的属性PiggyBank pb;Mother(PiggyBank pb) {this.pb=pb;}public void run() //母亲的行为是向储钱罐中放入10元钱,共计5次{for (int i = 1; i <= 5; i++){pb.put(i);System.out.println("妈妈向储钱罐中放第" + i+"个十元钱");}}}class Son extends Thread //儿子类,储钱罐是它的属性{PiggyBank pb;Son(PiggyBank pb){this.pb=pb;}public void run() //儿子的行为是从储钱罐中取钱,一次取10元,共计5次{for (int i = 1; i <= 5; i++){int number=pb.get();System.out.println("儿子从储钱罐中取第" + number+"个十元钱");}}}class PiggyBank //储钱罐类{private int number; //表示储钱罐中当前这张十元钱的编号synchronized int get(){return number;}synchronized void put(int i){number=i;}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。