Difference between wait-notify and CountDownLatch

后端 未结 1 1772
孤城傲影
孤城傲影 2021-02-03 14:26

I need some help understanding the advantages of using CountDownLatch over traditional wait-notify. I think notifyAll() indeed does the same thing, and it seems easier to use (m

相关标签:
1条回答
  • 2021-02-03 15:06

    They certainly don't do the same thing: CountDownLatch only signals when the event count has reached 0 and it does so automatically, wait-notify requires you to keep your own count if you want to achieve the same behavior. Implementing the same behavior is often error prone and it's best that you avoid it (especially if you're new to concurrency programming). Comparing CountDownLatch and wait-notify is hardly even an apples to oranges comparison, it's more like comparing an automatic drill and an Allen wrench.

    I don't know if you've used notifyAll() and CountDownLatch, but notifyAll() alone will not give you the same behavior unless you've kept count of how many events have occurred. CountDownLatch is probably most suitable for performing a fixed number of tasks and waiting for those tasks to complete before you resume execution of the rest of your program. It's especially helpful when you have a fixed number of threads (e.g. ThreadPool) executing a fixed number of tasks, but your threads are way fewer than the tasks and you have to reuse them. With a CountDownLatch you can easily wait for all of the tasks to be completed. I don't know how you've been using notifyAll() to achieve the same behavior, but if you provide us with more information we can address which one of the two is a better choice (there are certainly some cases where waitNotify() is more appropriate).

    Regarding the difference between wait() and await(), I'm somewhat disappointed in you! Looking up the documentation is step one of any question:

    http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html

    await() is an actual function of CountDownLatch whereas wait() is inherited from Object. I would recommend that you check the documentation for what they do.

    0 讨论(0)
提交回复
热议问题