2016-10-02 70 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