-
Notifications
You must be signed in to change notification settings - Fork 249
Open
Description
public class CountDownLatchExample {
private static final CountDownLatch latch = new CountDownLatch(4);
private static int data;
public static void main(String[] args) throws InterruptedException {
Thread workerThread = new Thread() {
@Override
public void run() {
for (int i = 1; i < 10; i++) {
data = i;
latch.countDown();
// 使当前线程暂停(随机)一段时间
Tools.randomPause(1000);
}
};
};
workerThread.start();
latch.await();
Debug.info("It's done. data=%d", data);
}
}
你在该代码的解释中说main线程的输出最终总是为4,这应该不准确吧,虽然countDown()调用前的操作对await()返回后的代码可见,但是考虑到main线程可能未分配时间片及时执行下面的输出的原因,workerThread线程是有可能更改共享变量data的(当然例子中使workerThread睡眠了1s几乎不可能出现main线程来不及执行,但这只能保证大部分情况data输出4),但是如果没有Tools.randomPause(1000);这行代码,data最终的值可能输出4~9之间的任何一个值。
Metadata
Metadata
Assignees
Labels
No labels