源碼如下:public?class?ThreadOfCommunication?{?public?static?void?main(String[]?args)?{??//?創(chuàng)建資源??Resource?resource2?=?new?Resource();??//?創(chuàng)建任務(wù)??Input?input?=?new?Input(resource2);??Output?output?=?new?Output(resource2);??//?創(chuàng)建線程,執(zhí)行路徑??Thread?thread1?=?new?Thread(input);??Thread?thread2?=?new?Thread(output);??//?開啟線程??thread1.start();??thread2.start();?}}/*?*?Resource(資源)?*/class?Resource?{?String?name;?String?sex;?boolean?flag=false;}/*?*?input(輸入)?*/class?Input?implements?Runnable?{?Resource?resource;?public?Input(Resource?resource)?{??this.resource?=?resource;?}?public?void?run()?{??int?x?=?0;??while?(true)?{???synchronized?(resource)?{????if(flag)?????wait();????if?(x?==?0)?{?????resource.name?=?"PIG";?????resource.sex?=?"MAN";????}?else?{?????resource.name?=?"麗麗";?????resource.sex?=?"女";????}????flag=true;????notify();???}???x?=?(x?+?1)?%?2;??}?}}/*?*?output(輸出)?*/class?Output?implements?Runnable?{?Resource?resource;?public?Output(Resource?resource)?{??this.resource?=?resource;?}?public?void?run()?{??while?(true)?{//?無限循環(huán)所以用while???synchronized?(resource)?{????if(!flag)?????wait();????System.out.println(??????Thread.currentThread().getName()?+?";刑滿釋放人員姓名::"?+?resource.name?+?";刑滿釋放人員性別:"?+?resource.sex);???}??}?}}求解?
添加回答
舉報
0/150
提交
取消