?? shop.java
字號:
public class Shop //定義一個商店類
{
private int breadNumber; //面包的數量,作為臨界資源
private int breadMaxSize; //商店里能存放面包的最大容量的個數
public int numberInWaitingPool; //shop對象的等待池中等待者的數量
public Shop(int breadMaxSize) //定義構造函數
{
this.breadMaxSize=breadMaxSize;
}
public synchronized void makeBread() //"生產面包"操作,對臨界資源的訪問
{
while (breadNumber==breadMaxSize) //商店中的面包已滿
{
try {
try{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
System.out.print( Thread.currentThread().getName()+"又想做新的面包...但是商店不能再放更多的面包了...所以");
System.out.println( Thread.currentThread().getName()+"被送入shop對象的等待池中.\n");
this.numberInWaitingPool++;
try{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
this.wait(); //當前線程進入等待狀態(即掛起狀態)
}
catch (InterruptedException e) {}
}
this.breadNumber++; //商店中面還能放面包,生產面包,則面包數量加1
try{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
System.out.print(" 商店還有"+this.breadNumber+"個面包.");
if (this.numberInWaitingPool>0) //等待池中有處于等待狀態的線程
{
this.notifyAll(); //隨機從shop對象的等待池中喚醒一個線程
System.out.print("(商店里面又有面包了,所以從shop對象的等待隊列中走出一個線程),");
this.numberInWaitingPool--; //等待池中線程數量減1
}
}
public synchronized void eatBread() //"吃面包"操作,對臨界資源的訪問
{
while(breadNumber==0){ //商店中已經沒有面包了
try {
try{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
System.out.print( Thread.currentThread().getName()+"又來吃了...但是商店已經沒有面包了...所以");
System.out.println(Thread.currentThread().getName()+"被送入shop對象的等待池中.");
this.numberInWaitingPool++;
this.wait(); //當前線程進入等待狀態,即掛起狀態
}
catch (InterruptedException e) {}
}
this.breadNumber--; //商店中若有面包,吃了一塊面包后,則其數量減1
try{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
System.out.print(" 商店還有"+this.breadNumber+"個面包.");
if (this.numberInWaitingPool>0) //等待池中有處于等待狀態的線程
{
this.notifyAll(); //隨機從shop對象的等待池中喚醒一個線程
System.out.print("(商店中空間有富余了.從shop對象的等待池中走出一個線程),");
this.numberInWaitingPool--; //等待池中現成數量減1
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -