[英]incrementing a static variable thru' 100 different threads without synchronisation, yet getting the final result as 100
[英]Incrementing Static variable with threads
我有许多客户,每个客户都有自己的线程。 我有一个咖啡馆对象,其中包含一个带有最多5个许可的信号灯。 客户在不同的时间到达和离开,因此我需要跟踪时间的流逝,一个客户在到达时从信号灯那里获得许可,在离开时从它那里释放。
客户实现可运行,将其称为咖啡馆的“吃”法。 我已经测试过,并且我的计数器正在增加到到达时间之上,但是没有调用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
变量的更改并非对所有线程可见。 为了确保所有线程读取相同的counter
值,必须使用volatile
。
static volatile int counter = 0;
有关更多信息,请参见Atomic Access和static与volatile 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.