廚師與服務生的問題

          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 © 久城

          主站蜘蛛池模板: 抚州市| 浏阳市| 雅安市| 武定县| 武汉市| 湾仔区| 潞城市| 东丽区| 龙游县| 长海县| 图片| 陵川县| 启东市| 南昌县| 日照市| 行唐县| 洛川县| 左权县| 永昌县| 利川市| 专栏| 电白县| 朝阳县| 靖西县| 潞西市| 曲阳县| 张家界市| 张家港市| 沙河市| 克什克腾旗| 班戈县| 雅安市| 习水县| 南溪县| 福泉市| 普定县| 从化市| 延津县| 兴国县| 卓资县| 尖扎县|