使用线程递增静态变量

Incrementing Static variable with threads

我有很多客户,每个客户都有自己的话题。我有一个咖啡馆对象,其中包含一个最多 5 个许可的信号量。客户在不同的时间到达和离开,所以我需要跟踪过去的时间,客户在到达时从信号量获取许可,在离开时释放它。

客户实现了runnable,调用了咖啡厅下面的'eat'方法。我已经测试过,我的计数器在到达时间以上递增,但是 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;
            }
        }
    }
}

客户的相关片段 Class

public class Customer implements Runnable{

    public void run() {
            icecream.eat(this);

}

main

的相关片段
 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变量的变化对所有线程不可见。要确保所有线程读取相同的 counter 值,您必须使用 volatile.

static volatile int counter = 0;

更多信息参见Atomic Access and static vs. volatile