In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "what is the way of wait-notify communication in Java thread communication". The editor shows you the operation process through an actual case, and the operation method is simple, fast and practical. I hope this article "what is the way of wait-notify communication in Java thread communication" can help you solve the problem.
1. Definition of thread communication
Thread is the smallest unit of operating system scheduling, which has its own stack space and can be executed step by step according to the established code, but if each thread runs in isolation, it will create a waste of resources. So in reality, if multiple threads are required to complete a task together according to the specified rules, then these threads need to coordinate with each other, which is called thread communication.
Thread communication can be defined as when multiple threads work together to operate shared resources, threads inform each other of their status in some way in order to avoid invalid competition for resources.
There are many ways to communicate between threads: wait-notify, shared memory, pipe flow. "wait-notify" communication is a common way of inter-thread communication in Java, and its classic case is the "producer-consumer" mode.
two。 Why do I need wait-notify?
Scene: several children want to enter the room and use the abacus (CPU) to calculate, so Lao Wang (operating system) uses a synchronized so that only one child can enter the room at a time, so they line up to enter the room.
(1) Xiaonan is the first to get the lock and enter the room, but because the conditions are not satisfied (no smoke can not work), Xiaonan can not continue to calculate, but if Xiaonan keeps occupying the lock, others will have to block all the time, and the efficiency is too low.
(2) so Lao Wang opened a lounge (call wait method) and asked Xiao Nan to wait in the lounge (WaitSet). At this time, the lock was released, and others could be randomly arranged by Lao Wang to enter the room.
(3) until Little M delivers the cigarette, shout [your cigarette has arrived] (call the notify method)
(4) Xiao Nan can then leave the lounge and re-enter the competitive lock queue.
The "wait-notify" inter-thread communication in java language is realized by wait () and notify () methods of objects. Each java object has two instance methods, wait () and notify (), and the wait () and notify () methods are closely related to the object's monitor.
There are more than two methods of wait () and notify () in number. The wait () and notify () methods do not belong to the Thread class, but to the java object instance.
3. Wait method and notify method
The wait () and notify () methods in the java object are like signal switches for the interaction between the waiting party and the notifying party.
1. The wait () method of the object
The main purpose of the object's wait () method is to block the current thread and wait for it to wake up. The wait () method is closely related to the object monitor and must be placed in the synchronization block when using the wait () method. The wait () method is called as follows:
Public class Main {static final Object lock = new Object (); public static void method1 () throws InterruptedException {synchronized (lock) {lock.wait ();}
There are three versions of the wait () method in the Object class:
(1) void wait (): after the current thread calls the wait () instance method of the synchronization object lock, it will cause the current thread to wait. The current thread enters the lock monitor WaitSet, waiting to be awakened by other threads.
(2) void wait (long timeout): wait for a limited time. Causes the current thread to wait, to be woken up by another thread, or to run out of timeout at a specified time, and the thread no longer waits
(3) void wait (long timeout,int nanos): time-limited waiting with high precision, its main function is to control the waiting time more accurately. The parameter nanos is an additional nanosecond wait time
2. Notify () method of the object
The main function of the object's notify () method is to wake up the waiting thread. The notify () method is closely related to the object monitor and needs to be placed in the synchronization block when calling the notify () method. The notify () method is called as follows:
Public class Main {static final Object lock = new Object (); public static void method1 () throws InterruptedException {synchronized (lock) {lock.notify ();}
There are two versions of the notify () method:
(1) void notify (): after lock.notify () is called, the first waiting thread in the lock monitor waiting set is awakened; the awakened thread enters the EntryList and its state changes from WAITING to BLOCKED.
(2) void notifyAll (): after lock.notifyAll () is called, it wakes up all waiting threads in the lock monitor waiting set, all awakened threads enter the EntryList, and the thread state changes from WAITING to BLOCKED.
Summary:
Obj.wait (): let threads entering the Object monitor wait on waitset
Obj.notify (): wake up one of the threads waiting for waitset on Object
Obj.notifyAll (): wakes up all threads waiting for waitset on the Object
4. The principle of wait method and notify method
The core principle of the object's wait () method is roughly as follows:
(1) when a thread calls the wait () method of lock (a synchronous lock object), jvm will add the current thread to the WaitSet (wait set) of the lock monitor, waiting to be woken up by other threads.
(2) the current thread releases the Owner rights of the lock object monitor so that other threads can seize the monitor of the lock object.
(3) Let the current thread wait and its state changes to WAITING. After the thread calls the wait () method of the synchronization object lock, the internal state of the monitor of the synchronization object lock is roughly shown in figure 2-15.
The principle of the notify () or notifyAll () method of an object is roughly as follows:
(1) when the thread calls the notify () method of lock (a synchronous lock object), jvm wakes up the first waiting thread in the lock monitor WaitSet.
(2) when the thread calls the notifyAll () method of lock, jvm wakes up all waiting threads in the lock monitor WaitSet.
(3) after the waiting thread is awakened, it moves from the WaitSet of the monitor to the EntryList, and the thread is qualified to queue to seize the rights of the monitor Owner, and its state changes from WAITING to BLOCKED.
(4) after the thread in EntryList grabs the Owner right of the monitor, the state of the thread changes from BLOCKED to Runnable and is qualified for re-execution.
(1) if the Owner thread finds that the condition is not met, call the wait method to enter WaitSet and become WAITING.
(2) both BLOCKED and WAITING threads are in a blocking state and do not occupy CPU time slices
(3) BLOCKED: the thread wakes up when the Owner thread releases the lock
(4) WAITING: the thread wakes up when the Owner thread calls notify or notifyAll, but it does not mean that the lock is acquired immediately. It still needs to enter the EntryList to re-compete.
5. Example of wait method and notify method 1. Only threads entering the Object monitor can call the wait () method
Xiao Nan can not directly enter the WaitSet lounge, but can only enter the lounge after obtaining the lock. Without the lock, Xiaonan can not enter the room, let alone enter the lounge. When he enters the break room, he releases the lock and allows other threads to compete for the lock to enter the room.
Public class Main {static final Object lock = new Object (); public static void main (String [] args) {synchronized (lock) {try {/ / only becomes the owner of the monitor object, that is, after the object lock is acquired, it is eligible to enter waitset and wait for lock.wait ();} catch (InterruptedException e) {e.printStackTrace () 2. Only threads entering the Object monitor can call the notify () method
At this time, Xiao M got the lock, entered the room, and awakened Xiao Wang who was waiting in the break room. Xiao M could not wake up Xiao Wang waiting in the break room when he got the lock, because Xiao M was outside the door at this time. Xiao Wang can't hear you at all.
Use notify () to wake up a thread in the waiting area:
Public class Main {static final Object lock = new Object (); public static void main (String [] args) throws InterruptedException {Thread T1 = new Thread (()-> {System.out.println ("T1 thread starts execution...") Synchronized (lock) {try {/ / Let the T1 thread wait for lock.wait () in the waitset of the lock lock;} catch (InterruptedException e) {e.printStackTrace () } / / after being awakened, continue to execute System.out.println ("Thread T1 awakened.");}}, "T1"); t1.start (); Thread T2 = new Thread (()-> {System.out.println ("T2 thread starts execution.") Synchronized (lock) {try {/ / Let the T2 thread wait for lock.wait () in the waitset of the lock lock;} catch (InterruptedException e) {e.printStackTrace () } / / after being woken up, continue to execute System.out.println ("Thread T2 wakes up...");}, "T2"); t2.start (); Thread.sleep (2000); System.out.println ("Wake up the waiting thread on the lock lock.") Synchronized (lock) {/ / after the main thread gets the lock, it wakes up a thread that is waiting in the break room lock.notify ();}
Execution result:
The T1 thread starts execution.
The T2 thread starts execution.
Wake up the waiting thread on the lock lock.
Thread T1 is awakened.
Use notifyAll () to wake up all threads in the waiting area:
Public class Main {static final Object lock = new Object (); public static void main (String [] args) throws InterruptedException {Thread T1 = new Thread (()-> {System.out.println ("T1 thread starts execution...") Synchronized (lock) {try {/ / Let the T1 thread wait for lock.wait () in the waitset of the lock lock;} catch (InterruptedException e) {e.printStackTrace () } / / after being awakened, continue to execute System.out.println ("Thread T1 awakened.");}}, "T1"); t1.start (); Thread T2 = new Thread (()-> {System.out.println ("T2 thread starts execution.") Synchronized (lock) {try {/ / Let the T2 thread wait for lock.wait () in the waitset of the lock lock;} catch (InterruptedException e) {e.printStackTrace () } / / after being woken up, continue to execute System.out.println ("Thread T2 wakes up...");}, "T2"); t2.start (); Thread.sleep (2000); System.out.println ("Wake up the waiting thread on the lock lock.") Synchronized (lock) {/ / after the main thread gets the lock, it wakes up all threads waiting in the break room lock.notifyAll ();}
Execution result:
The T1 thread starts execution.
The T2 thread starts execution.
Wake up the waiting thread on the lock lock.
Thread T2 is awakened.
Thread T1 is awakened.
6. Why are the wait and notify methods called in the synchronization block?
When calling the wait () and notify () series methods of a synchronization object, the "current thread" must have a synchronization lock for the object, that is, the wait () and notify () series methods need to be used in the synchronization block, otherwise JVM will throw an exception similar to the following:
Why is it that wait and notify are not used internally in synchronized synchronization blocks to throw exceptions? This starts with the principles of the wait () and notify () methods.
The principle of the wait () method:
First, JVM releases the Owner qualification of the current thread's object lock monitor; second, JVM moves the current thread into the monitor's WaitSet queue, and these operations are related to the object lock monitor. Therefore, the wait () method must be called inside the synchronized synchronization block. Before the current thread executes the wait () method, it must be the Owner of the monitor of the object lock through the synchronized () method.
The principle of the notify () method:
JVM moves a thread from the WaitSet queue of the object lock monitor to its EntryList queue, all of which are related to the object lock monitor. Therefore, the notify () method must also be called inside the synchronized synchronization block. Before executing the notify () method, the current thread must also become the Owner of the object lock monitor through the synchronized () method.
This is the end of the introduction to "how wait-notify communicates in Java thread communication". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.