题目:在饭店中,厨师需要做十道菜。厨师做好一道菜,就招呼侍者端走,菜还没有端走时,厨师就睡觉。侍者端走菜时把厨师唤醒,厨师做下一道菜。无做好的菜,侍者就睡觉。请编写程序模拟厨师和侍者的合作。(提示:厨师线程控制程序的结束,侍者线程不能控制程序结束。否则就是多头控制,影响程序的可维护性。
文章目录
废话不多说,直接上代码主函数测试类厨师线程类设计侍者线程类设计餐馆类设计废话不多说,直接上代码
主函数测试类
package T3;/*** @author 胖胖的山头* @create -10-24 14:51*/public class RestaurantTest {public static void main(String[] args) {Restaurant restaurant=new Restaurant();Chef chef = new Chef(restaurant);Waiter waiter = new Waiter(restaurant);chef.setName("厨师");waiter.setName("侍者");chef.start();waiter.start();}}
厨师线程类设计
package T3;/*** 厨师线程** @author 胖胖的山头* @create -10-24 14:52*/public class Chef extends Thread{private Restaurant restaurant=new Restaurant();public Chef(Restaurant restaurant) {this.restaurant=restaurant;}@Overridepublic void run() {while (true){try {sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}if(restaurant.getCount()<10){restaurant.cook();}else {System.out.println("上菜结束。。欢迎下次光临");break;}}}}
侍者线程类设计
package T3;/*** @author 胖胖的山头* @create -10-24 14:53*/public class Waiter extends Thread{private Restaurant restaurant=new Restaurant();public Waiter(Restaurant restaurant) {this.restaurant=restaurant;}@Overridepublic void run() {while (true){try {sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}restaurant.serving();if (restaurant.getCount()==10){break;}}}}
餐馆类设计
package T3;/*** 餐馆** @author 胖胖的山头* @create -10-24 14:55*/public class Restaurant {private int greens=0;private int count=0;public int getCount() {return count;}public int getGreens() {return greens;}public synchronized void cook(){if (greens==0){greens++;count++;notify();System.out.println(Thread.currentThread().getName()+":做好了第"+count+"道菜");}else{try {wait();} catch (InterruptedException e) {e.printStackTrace();}}}public synchronized void serving(){if (greens>0) {greens--;notify();System.out.println(Thread.currentThread().getName() + ":上了第" + count + "道菜");}else{try {wait();} catch (InterruptedException e) {e.printStackTrace();}}}}
在饭店中 厨师需要做十道菜。厨师做好一道菜 就招呼侍者端走 菜还没有端走时 厨师就睡觉。侍者端走菜时把厨师唤醒 厨师做下一道菜。无做好的菜 侍者就睡觉。请编写程序模拟厨师和侍者的合作。(提示:厨师线程
如果觉得《在饭店中 厨师需要做十道菜。厨师做好一道菜 就招呼侍者端走 菜还没有端走时 厨师》对你有帮助,请点赞、收藏,并留下你的观点哦!