Languages
[Edit]
EN

Java concurrency - avoid busy wait using wait() and notify() inter-thread communication methods

7 points
Created by:
maxsior322
347

In this article, we would like to show to to avoid busy wait using wait() and notify() inter-thread communication methods in Java.

Note: the preseted approach is not the best choice to synchronize threads, but in this post we use it for learning purpose.

Quick solution:

 

Practical example

Edit

The main idea of the presented solution is to use synchronized keyword to control and exchange tasks state between threads. It prevents against same-time critical sections execution by different threads. counter object helps to detect when all tasks are done. The main thread waits for notification from other threads when some task is done - when notify() is called, wait() method is unblocekd once.

Warning:

It is not good idea to use wait() and notify() methods, because there is always risk the notify() will be executed before wait() leaving program blocked.

Source code: 

Output:

 

See also

Edit
  1. What is busy waiting lock?

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java concurrency

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join