The Notify,wait,notifyall of Object

Source: Internet
Author: User

The first thing to note is that declaring the method declared in the object class is a feature that every Java class should have, because it is well known that object is the originator of all Java classes, so what are the three methods in object? One sentence summary: Used to control the state of Java threads, or to do thread synchronization.


First of all, learn three basic concepts,

Thread synchronization: Multi-threaded concurrent completion of tasks, may require the execution of threads between the sequencing, thread A does the task must wait for thread B to complete before it can be done.

Thread Mutex: Multiple threads execute concurrently, and only one thread can perform a task at the same time, typically in the execution of a code snippet, such as when a thread accesses a class method, the B thread should not be able to access the method at the same time because the method internally accesses a thread-unsafe container, such as ArrayList, If you access this function at the same time will cause ArrayList data inconsistency, simple point is management chaos.

Seven states of Java threads: New, Dead, runnable, running, timed_waiting, waiting, blocked

After understanding the above concepts, we see how the JVM implements the mutex and synchronization of threads:

The Java implementation of this thread of synchronization and thread mutual exclusion is accomplished through object locks, known as the Synchronized keyword, through which it is able to lock an object (possibly an instance object, or a class object "Note: Static lock"), This locking makes it easy to implement multi-threaded mutual exclusion, which is roughly the case:

1, the thread enters a code snippet stating the Synchronized keyword must obtain the lock of the declared object, there is a built-in lock inside every object in Java, the JVM is responsible for modifying the information that the lock is occupied by which thread

2. If the lock of the object is not occupied, the current thread acquires the object lock, the JVM modifies the information, and the thread can continue to execute the code snippet in synchronized, at which point the thread is in the runnable or running state (the difference is whether the CPU time is obtained)

3. If the object lock is already occupied by another thread, the Java Virtual machine pauses the current request thread to run, leaving it in the blocked state. The thread scheduler of the Java Virtual Machine is responsible for placing the thread that is waiting for the lock into the runnable pool and assigning the object lock to it when the thread that takes the lock is running, and the blocked thread is in the Runnabel state. Wait for the CPU time to continue running (running).

What's the problem now? Through the above analysis we found that through the synchronized can only achieve the mutual exclusion between threads, then the multi-line synchronization problem how to solve, through the above analysis we found that a thread of the stop and start are not affected by their own active control, but through the lock mechanism by the Java Virtual machine passive scheduling. This obviously does not implement the mechanism of thread synchronization, so the JVM introduces a wait, notify mechanism to solve this problem.

The first thing to declare is that wait and notify are designed based on object locks, so you must first obtain an object lock when you execute the wait and notify methods. The following are the basic steps for thread synchronization:

(1) Assuming that thread A is running in the running state, it wants to stop running, wait for thread B to run out of synchronization code, and then it comes back and then runs, obviously this stop to have some kind of token, to inform thread B after the execution of a certain code can be recalled, So first, thread A is going to get an object lock L (the built-in lock for any object can).

(2) When I get the L, thread a executes wait,wait's design where it wants to stop running, in order to solve this problem, in fact, the core of wait is just two things: 1, releasing the object lock that the current thread has acquired L;2, The JVM puts this thread from running to wating or timed_waiting state, in fact, the object lock L is the mark in (1), wait to release the object lock actually tells the JVM when it is in the waiting state waiting for what (in fact, the object lock L)

(3) A after the object lock is freed by wait, because B is getting the object lock before synchronizing the block of code, it is in the blocked state before a release of the object lock, and a after releasing the object lock it is changed from the blocked state to the runnable state. After obtaining the CPU time, the running state is changed and the object lock L is obtained, and the synchronization code block is entered.

(4) and notify's role is to inform the JVM will wait for the same object to lock the thread as to the blocked state, only this, no other, do not think notify itself will release the function of the object lock, no it does just modify the state of the waiting thread, Thread B changed the state of thread A to blocked after executing notify.

(5) thread B continues to run until all of the synchronization blocks have been completed, at which point the JVM frees up B for the object lock L, and the JVM chooses thread A to wait for that object lock from all threads in the blocked state and modifies its state to runnable (probabilistic selection).

(6) Thread A gets the CPU time and continues the wait after the code runs

The following examples illustrate the above process:

First I randomly wrote a mutex object for the mutex object

Package Com.wanyonghui.test.notify;public class Mutex {}

Then define two threads, one corresponding to thread a above, and one corresponding to thread B above

Package com.wanyonghui.test.notify;/* * This line enters upgradeable a word "I am thread waitthread begin" and then waits for the notifytread thread to finish the task before printing another sentence " I am thread Waitthread end "*/public class Waitthread extends Thread{private mutex mutex;public waitthread (mutex mutex) { This.mutex = Mutex;} public void Run () {try {System.out.println ("I am thread waitthread begin"), synchronized (mutex) {mutex.wait ();} System.out.println ("I am thread Watithread end");} catch (Interruptedexception e) {e.printstacktrace ();}}}


Package com.wanyonghui.test.notify;/* * This thread goes to bed for 3 seconds, then a word "I am thread notifythread processing" and finally wakes up another thread "*/public class Notifythread extends Thread{private mutex mutex;public notifythread (mutex mutex) {This.mutex = mutex;} public void Run () {try {Thread.Sleep]; synchronized (mutex) {System.out.println ("I am thread notifythread processing"); Mutex.notify (); Thread.Sleep (3000);}} catch (Interruptedexception e) {e.printstacktrace ();}}}

Here is the test class

Package Com.wanyonghui.test.notify;public class Testnotify {public static void main (string[] args) {Mutex mutex = new Mute X (); Notifythread wt = new Notifythread (mutex); Waitthread NT = new Waitthread (mutex); Wt.start (); Nt.start ();}}

Operation Result:

I'm thread Waitthread begin (3 seconds to show next line)

I am thread notifythread processing (3 seconds to show next line)

I am the thread watithread end







The Notify,wait,notifyall of Object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.