Java Multi-thread Wait (), notify,notifyall (), yield ()

Source: Internet
Author: User

Wait (), notify (), Notifyall () are not part of the thread class, but belong to the object base class, which means that each pair has wait (), notify (), Notifyall ()
function. Because all have a lock on the image, the lock is the basis of each pair of image, of course, the method of operation lock is the most basic.

wait and notify are an important part of the Java synchronization mechanism. Combined with synchronized keyword use, you can build many excellent synchronization models.
synchronized (this) {} is equivalent to publicsynchronized void method () {...}
synchronization is divided into class level and object level, which correspond to class lock and object lock respectively. Class locks are only one per class, and if the static method is modified by the Synchronized keyword, the class lock must be obtained before the method is executed; object locks are similar.
first, when you invoke the wait and Notify/notifyall of an object, you must ensure that the calling code is synchronous with the object, that is, it must be equal to synchronized (obj) {...} To call obj's wait and notify/notifyall three methods, otherwise it will be an error:
java.lang.IllegalMonitorStateException:current Thread not owner
When you call wait, the thread automatically releases its occupied object lock and does not request an object lock. When the thread is awakened, it gets the right to acquire the object lock again.
So, there is not much difference between notify and Notifyall, except that notify only wakes up one thread and allows it to acquire a lock, Notifyall is to wake up all the threads waiting for the object and allow them to get the object lock, as long as the code in the Synchronied block , there is no object lock is unable to do. In fact, waking up a thread is a way to re-allow this thread to get the object lock and run down.

Notifyall, although it is called once for each wait object notify, but this is still in order, each object holds this waiting object chain, the order of the call is the order of the chain. In fact , it is also a thread to start the various threads in the waiting object chain, which needs to be noted in the specific application.

Wait ():

Wait for the object's synchronization lock, need to obtain the object's synchronization lock to call this method, otherwise the compilation can pass, but the runtime will receive an exception: Illegalmonitorstateexception.

Calling the Wait () method of an arbitrary object causes the thread to block, the thread cannot continue execution, and the lock on the object is freed.

Notify ():

Wake up the thread waiting for the object to synchronize the lock (wake only one, if there are multiple waits), note that when this method is called, it does not wake up the thread of a waiting state exactly, but is determined by the JVM to wake up which thread, and not by priority.

Calling the Notify () method of an arbitrary object causes a randomly selected unblocking in a thread that is blocked by calling the wait () method of the object (but is not really executable until the lock is acquired).

Notifyall ():

Wake up all waiting threads, notice that the thread that wakes up is notify before wait, and has no effect on the wait thread after notify.

Yield ():

This method is similar to sleep (), except that it is not possible for the user to specify how long to pause, and the yield () method only allows the same priority thread to have an opportunity to execute.

Changes the current thread from the execution state (running state) to the executable (ready state). The CPU is chosen from a multitude of executable states, that is, the thread that is just now is still likely to be executed again, not necessarily executing another thread and the thread will not execute the next time.

there is a Thread.yield () method in the Java thread that many people translate into threading concessions. As the name implies, that is, when a thread uses this method, it takes its CPU time off and lets itself or other threads run.

Example:

 PackageCom.yield; Public classYieldtestextendsThread { Publicyieldtest (String name) {Super(name); } @Override Public voidrun () { for(inti = 1; I <= 50; i++) {System.out.println ("" + This. GetName () + "-----" +i); //when I is 30 o'clock, the thread will get rid of the CPU time and let the other or its own threads execute (i.e. who first grabs the execution)            if(i = = 30) {                 This. Yield (); }        }    }      Public Static voidMain (string[] args) {yieldtest yt1=NewYieldtest ("Zhang San"); Yieldtest yt2=NewYieldtest ("John Doe");        Yt1.start ();    Yt2.start (); }}

Operation Result:

The first case: John Doe (thread) when execution to 30 o'clock CPU time to let go, then Zhang San (thread) to grab CPU time and execute.

Second case: John Doe (thread) when execution to 30 o'clock CPU time is dropped, then John Doe (thread) Grab CPU time and execute

In general, there is a need for coordination between multithreading: if the condition is not met, wait, and when the condition is met, the thread that waits for the condition is awakened. In Java, the implementation of this mechanism relies on wait/notify. The wait mechanism is closely related to the lock mechanism.

For example:
synchronized (obj) {
While (!condition) {
obj.wait ();
}
obj.dosomething ();
}
  
when thread a obtains the obj lock, it finds that the condition condition is not satisfied and cannot proceed to the next processing, so thread A is wait ().
in another thread B, if B changes some conditions so that thread A's condition condition satisfies, it can wake up thread A:
  
synchronized (obj) {
condition = true;
obj.notify ();
}
  
the concepts to be aware of are:  
  
# before invoking the Wait (), notify () method of obj, you must obtain the obj lock, which must be written in the synchronized (obj) {...} code snippet.

  
# after calling obj.wait (), thread a releases the lock on obj, otherwise thread B cannot get the obj lock and cannot wake a within the synchronized (obj) {...} code snippet.
  
# when the Obj.wait () method returns, thread a needs to obtain the OBJ lock again to continue execution.
  
#如果A1, A2,a3 is obj.wait (), the B call Obj.notify () wakes only one of the a1,a2,a3 (whichever is determined by the JVM).
  
#obj. Notifyall () can wake all a1,a2,a3, but to continue executing the next Statement of Obj.wait (), the obj lock must be obtained, so A1,A2,A3 has only one chance to get a lock to continue execution, such as A1, The rest needs to wait for A1 to release the obj lock before it can continue execution.
  
# When B calls Obj.notify/notifyall, B is holding the obj lock, so the A1,A2,A3 is awakened, but the obj lock is still not available. Until B exits the synchronized block, after releasing the obj lock, one of the A1,A2,A3 has the opportunity to get the lock to continue execution.
  

Talk about the relationship between synchronized and wait (), notify (), and so on:

1. There is not necessarily a wait,notify in a synchronized place.

2. There must be synchronized where there is wait,notify. This is because wait and notify are not thread classes, but are methods that each object has, and both methods are related to object locks, and there must be synchronized in place of locks.

Also, note that if you want to put the notify and wait methods together, you must call wait after calling notify, because if you finish calling wait, the thread is not currentthread.

The state of the thread
Threads have four states, and any one thread must be in one of these four states:
1) Generation (NEW): The thread object has been generated but has not been started and cannot be executed. If a thread object is generated through new, it is not called before the start () function.
2) executable (Runnable): Each multithreaded system has a scheduler that selects a thread from the thread pool and starts it. When a thread is in an executable state, it indicates that it may be in the thread pool waiting for the scheduler to start it, or it may already be executing. If the start () method of a thread object is executed, the thread is in an executable state, but it is clear that the thread is not necessarily executing at this point.
3) Death (Dead): When a thread ends normally, it is in a dead state. A thread enters a dead state when the run () function of a thread finishes executing.
4) Stagnation (Blocked): When a thread is stuck, the system scheduler ignores it and does not schedule it. It is possible to re-execute a stalled thread when it is back in the executable state. If you call the Wait () function on a thread, the thread goes to a standstill, and it can return to the executable state two times after two calls to the thread notify or Notifyall.

Java Multi-thread Wait (), notify,notifyall (), yield ()

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.