我已经开发了一个样本Java程序来了解countdownlatch并使用count 4初始化了countdownlatch。我希望在countDown方法之后,getCount()将返回countdownlatch的剩余计数。但是,在以下示例中:-
public static void main(String args[]) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(4);
Worker first = new Worker(latch, "WORKER-1");
Worker second = new Worker(latch, "WORKER-2");
Worker third = new Worker(latch, "WORKER-3");
Worker fourth = new Worker(latch, "WORKER-4");
first.start();
second.start();
third.start();
fourth.start();
latch.await();
System.out.println("Final Count:- " + latch.getCount());
}
}
class Worker extends Thread {
private CountDownLatch latch;
public Worker(CountDownLatch latch, String name) {
super(name);
this.latch = latch;
}
@Override
public void run() {
latch.countDown();
System.out.println("Count:- " + latch.getCount());
System.out.println(Thread.currentThread().getName() + " finished");
}
}
输出为:-
数:-2
数:-1
数:-2
WORKER-3完成
WORKER-1完成
WORKER-2完成
计数:-0
最终计数:-0
WORKER-4完成了。
该计数在输出中两次返回2。我的代码有什么问题吗?
答案 0 :(得分:0)
这不是问题。 request or session scope
此方法仅读取volatile
,而不读取synchronised
。
/**
* Returns the current count.
*
* <p>This method is typically used for debugging and testing purposes.
*
* @return the current count
*/
public long getCount() {
return sync.getCount();
}
答案 1 :(得分:0)
四个Worker
同时运行。由于latch.countDown();
和latch.getCount()
不是原子的,因此执行顺序可能是:
thread1 latch.countDown();
thread2 latch.countDown();
thread1 System.out.println("Count:- " + latch.getCount()); // Count:- 2
thread2 System.out.println("Count:- " + latch.getCount()); // Count:- 2