最基本的多線程的實現...看寢室的兄弟們學到多線程了,自己也回憶回憶!
/**
*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僅用于個人學習交流!
目的在于記錄個人成長.
所有文字均屬于個人理解.
如有錯誤,望多多指教!不勝感激!