廚師與服務(wù)生的問題

          Posted on 2006-10-22 14:11 久城 閱讀(351) 評論(0)  編輯  收藏 所屬分類: JavaTest

          最基本的多線程的實現(xiàn)...看寢室的兄弟們學(xué)到多線程了,自己也回憶回憶!

          /**
          *title 用多線程實現(xiàn)廚師與服務(wù)生的問題
          *@author:realsmy
          *date 2006-10-22 14:10
          */
          public class Test{
          ?public static void main(String args[]){
          ??CanGuan c=new CanGuan();
          ??new Thread(new ChuShi(c)).start();
          ??new Thread(new FuWuSheng(c)).start();
          ?}
          }

          //廚師一直執(zhí)行餐館類的set()方法
          class ChuShi implements Runnable{
          ?CanGuan c;
          ?public ChuShi(CanGuan c){
          ??this.c=c;
          ?}
          ?public void run(){
          ??while(true){
          ???c.set();???
          ??}????
          ?}?
          }

          //服務(wù)生一直執(zhí)行餐館類的get()方法
          class FuWuSheng implements Runnable{
          ?CanGuan c;
          ?public FuWuSheng(CanGuan c){
          ??this.c=c;
          ?}
          ?public void run(){
          ??while(true){
          ???c.get();
          ??}
          ?}?
          }

          class CanGuan
          {
          ?private boolean b = true;
          ?private int i =1;
          ?public synchronized void set()
          ?{
          ??if(!b)
          ???try{
          ????wait();
          ???}catch(Exception e){}
          ???System.out.println("廚師做好了菜"+i);
          ???try{
          ????Thread.sleep(1000);
          ???}catch(Exception e){}
          ???b = false;
          ???notify();
          ??
          ?}
          ?public synchronized void get()
          ?{
          ??if(b)
          ???try{
          ????wait();
          ???}catch(Exception e){}
          ???System.out.println("服務(wù)生取走了菜"+i);
          ???i++;
          ???try{
          ????Thread.sleep(1000);
          ???}catch(Exception e){}
          ???b = true;
          ???notify();??
          ?}
          }



          歡迎來訪!^.^!
          本BLOG僅用于個人學(xué)習(xí)交流!
          目的在于記錄個人成長.
          所有文字均屬于個人理解.
          如有錯誤,望多多指教!不勝感激!

          Copyright © 久城

          主站蜘蛛池模板: 新沂市| 新巴尔虎右旗| 遂宁市| 睢宁县| 阿瓦提县| 诸暨市| 丰镇市| 岚皋县| 茌平县| 乐都县| 灵寿县| 镇平县| 蒙自县| 江油市| 黄骅市| 姜堰市| 江西省| 平邑县| 浦县| 曲阜市| 工布江达县| 峨山| 交城县| 新和县| 张北县| 沙雅县| 禹州市| 宁安市| 舟曲县| 革吉县| 平顺县| 延安市| 永嘉县| 伽师县| 怀仁县| 广元市| 沧源| 米泉市| 安泽县| 苗栗市| 武川县|