Posted on 2006-10-22 14:11
久城 閱讀(340)
評論(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í)交流!
目的在于記錄個人成長.
所有文字均屬于個人理解.
如有錯誤,望多多指教!不勝感激!