This post would demo how to do the basic thread communication, e.g. the producer and consumer mode.
Normally, we would have a producer thread to produce something, and another consumer thread to consume the products.
2.1 Basic wait-notify threads code template
To implement the basic producer and consumer threads, you can use the wait-notify mode, the code template is as follows:
2.2 Basic producer/consumer thread example
- line 1: this is the condition variable to be shared by both consumer and producer threads
- line 2: the lock object to be used for synchronization of the threads
- line 3 and line 4: After call producer and consumer threads, we call the join from main thread, this would let the main thread to wait for the threads to complete before main exit
Run the code, we get the result:
2.3 The other notifications about wait/notify
- wait() 、nofify() 、nofityAll(): you must accquire the lock to call these methods
- After call object.wait(), the object’s lock would be released, the current thread is moved to the WAITING queue.
- After call object.notify(), the current thread would be moved to the synchronized queue,and status changed to BLOCKED.
- After call notify(), you should release the lock, otherwise ,the WAITING thread would still wait.
I would write more examples about inter-threads communication.
In this post we demoed how to iterate a Map by using various methods.You can find the whole code examples on github project, the class source code is located at this
You can find detail documents about the java stream here: