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; 
      } 
     } 
    } 
} 

顧客クラスの関連スニペット

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(); 

の関連スニペットすべてのヘルプはcounter変数の

+0

お客様とメインの実装を見ずに何が間違っているのかを知るのは難しいです。 –

+0

try catchブロックが呼び出されないとき、私はcustomer.getArrivalTime()

+0

'if(customer.getArrivalTime()

答えて

1

変更はすべてに表示されていないいただければ幸いですスレッド。すべてのスレッドが同じcounter値を読み取っていることを確認するには、volatileを使用する必要があります。

static volatile int counter = 0; 

詳細はAtomic Accessstatic vs. volatileを参照してください。