0
我有許多客戶,每個客戶都有自己的線程。我有一個咖啡館對象,其中包含最多5個許可證的信號量。客戶在不同的時間到達並離開,所以我需要跟蹤時間流逝,客戶在信號量到達時獲得許可,並在離開時釋放。使用線程遞增靜態變量
客戶實現了runnable,這就是咖啡廳下面的「吃飯」方法。我已經測試過,並且我的計數器在到達時間之上遞增,但try/catch語句沒有被調用。
public void eat(Customer customer)
{
while(true) {
System.out.println("hello");
if (customer.getArrivalTime() < Main.counter) {
try {
semaphore.acquire();
System.out.println(customer.getName() + ' ' + customer.getArrivalTime());
TimeUnit.SECONDS.sleep(customer.getLeavetime());
} catch (InterruptedException iex) {
iex.printStackTrace();
} finally {
//System.out.printf("Farmer %s has crossed the bridge.\n",customer.getName());
semaphore.release();
System.out.println(Main.counter);
break;
}
}
}
}
Customer類的相關片段
public class Customer implements Runnable{
public void run() {
icecream.eat(this);
}
的主要
public class Main {
static int counter = 0;
static Timer timer;
public static void main(String[] args) {
//create timer task to increment counter
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
// System.out.println("TimerTask executing counter is: " + counter);
counter++;
}
};
Customer c1 = new Customer(Parlor, 5); //arrival time of 5
Thread t1 = new Thread(c1);
timer = new Timer("MyTimer");//create a new timer
timer.scheduleAtFixedRate(timerTask, 1000, 1000); //start timer to increment counter
t1.start();
相關片段任何幫助,將不勝感激
沒有看到客戶和主要實施,很難說出什麼問題。 –
當try catch塊沒有被調用時,我會假設customer.getArrivalTime()
'if(customer.getArrivalTime()