2016-10-02 86 views
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(); 

相關片段任何幫助,將不勝感激

+0

沒有看到客戶和主要實施,很難說出什麼問題。 –

+0

當try catch塊沒有被調用時,我會假設customer.getArrivalTime()

+0

'if(customer.getArrivalTime()

回答

1

counter變量的變化是不是所有可見線程。爲確保所有線程讀取的值相同,您必須使用volatile

static volatile int counter = 0; 

更多信息請參閱Atomic Accessstatic vs. volatile