廚師與服務生的問題

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

          最基本的多線程的實現...看寢室的兄弟們學到多線程了,自己也回憶回憶!

          /**
          *title 用多線程實現廚師與服務生的問題
          *@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();
          ?}
          }

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

          //服務生一直執行餐館類的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("服務生取走了菜"+i);
          ???i++;
          ???try{
          ????Thread.sleep(1000);
          ???}catch(Exception e){}
          ???b = true;
          ???notify();??
          ?}
          }



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

          Copyright © 久城

          主站蜘蛛池模板: 沂南县| 财经| 额敏县| 安化县| 钟祥市| 龙泉市| 资源县| 饶阳县| 德化县| 泗阳县| 赫章县| 绵竹市| 阿瓦提县| 棋牌| 渭南市| 瑞金市| 五台县| 县级市| 安阳市| 东城区| 仁怀市| 大同市| 沾益县| 贵南县| 原阳县| 临澧县| 屏东县| 宣化县| 海门市| 汝阳县| 昭觉县| 庄河市| 德化县| 长岛县| 云安县| 伊川县| 甘南县| 磐安县| 吉水县| 家居| 呈贡县|