简体   繁体   English

如何知道闩锁是否完成了任务

[英]How to know if a latch finished its task

I have two threads with countDownLatch set to 1, so that, when the first threads finishes the second should starts. 我有两个将countDownLatch设置为1的线程,因此,当第一个线程完成时,第二个线程应该启动。 And what I want to do is, when the second finishes its task, I want to get the data computed from both threads to do some operations. 我想做的是,当第二个任务完成时,我想从两个线程中计算出数据来执行一些操作。

now my question is, is there any way to know if the CountDownLatch object finished its task? 现在我的问题是,有什么办法知道CountDownLatch对象是否已完成其任务?

Update 更新资料

is it safe to use 使用安全吗

while (latch.getcountDown()==0) {
 // do the calculations on the data processed by the two threads
}

Yes when your thread finishes and is capable of say accepting request or a particular task, it call countDown method on latch. 是的,当您的线程完成并且可以说接受请求或特定任务时,它将在闩锁上调用countDown方法。 And on the other hand in your main thread (or your co-ordinator thread), block on await method on latch. 另一方面,在您的主线程(或协调线程)中,在闩锁的await方法上阻塞。

Now whenever 'x' slave threads completes their task and calls countDown, master knows about the same and comes out of await and does further processing. 现在,每当“ x”个从属线程完成其任务并调用countDown时,主线程就知道这一点,并且退出等待状态并进行进一步处理。

Have you tried 'join' for the threads. 您是否尝试过“加入”线程。 Instead of using a heavy latch join might do the trick. 代替使用繁重的闩锁连接可能会成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM