Java Inter-threading collaboration: WAIT.NOTIFY.NOTIFYALL

Source: Internet
Author: User
Tags object object

Java's process synchronization is implemented through synchronized (), and it should be explained that the Java synchronized () method is similar to the mutually exclusive block of memory in the operating system concept. In the type of object in Java. Are all with a memory lock, after the thread acquires the memory lock. Other threads cannot access the memory. In order to achieve simple synchronization in Java, mutually exclusive operation.

Clear this principle. You can understand why synchronized (this) differs from synchronized (static XXX). Synchronized is to request a memory lock for the memory block, Thiskeyword represents an object of the class, so its memory lock is a mutually exclusive operation against the same object, and the static member belongs to the class proprietary, and its memory space is shared by all members of the class. This results in synchronized () locking the static member, which is equivalent to locking the class, which is mutually exclusive among all members of the class. At the same time, only one thread can access an instance of the class.

Let's just say that the simple truth is that threads in Java now repel each other, and it's enough to be clear about these basics.

However, assuming that collaborative communication between threads is required, the wait,notify and Notifyall methods of Object objects are needed.

In Java. Collaborative communication between threads can be achieved by using the Wait method and the Notify method or the Notifyall method to invoke object objects. Call the wait method in the thread. will block notifications waiting for other threads (other threads call the Notify method or the Notifyall method), call the Notify method or the Notifyall method in the thread, and notify other threads to return from the wait method. Object. Wait () andObject. Notify () must be used with a synchronous block or synchronous method (synchronized block or Synchronized method), that is, wait and notify are for already acquiredObjectThe lock, from a grammatical point of view, isObject. Wait (),ObjectThe. Notify must besynchronous block or synchronous methodWithin Functionally, wait means that the thread acquires the object lock. Actively releasing object locks. This thread sleeps at the same time. The thread continues to acquire an object lock until another thread calls the object's notify () to wake it. and continue to run.

The corresponding notify () is the wake-up operation of the object lock.

One thing to note, however, is that the Notify () call does not immediately release the object lock, but instead runs at the end of the corresponding synchronization block or synchronous method , releasing the lock on its own initiative. The JVM randomly selects a thread in the Wait () object lock to give its object a lock. Wakes the thread and continues to run. This provides a synchronous, wake-up operation between threads. Both Thread.Sleep () and object.wait () can pause the current thread and release the CPU control, the basic difference being that the object.wait () is released at the same time as the CPU. The control of the object lock is freed.

Wait Method

When calling the thread's Sleep,yield method, the thread does not yield the object lock, but wait is different.

The wait function must be called in a synchronous code block (that is, the current thread must hold the lock on the object), which is the function:

I'm tired. Rest for a while. The lock of the object you take to use it. The CPU is also given to you.

The thread that called the wait function waits until another thread calls the notify of the same object or the Notifyall method is awakened, and it is important to note that being awakened does not mean getting the object's lock immediately. That is, after a thread invokes the object's wait method, he needs to wait for two things to happen:

1. There are other threads calling the Notify or Notifyall method of the same object (before calling the Notify/notifyall method) 2. Gets the lock on the object again after it has been awakened (after calling the Notify/notifyall method)ability to continue to run down the action.

Suppose a thread invokes the wait method for an object, but perhaps no other thread calls the object's notify or Notifyall method. Then the thread will wait forever ...

notify and Notifyall methods

The Notify/notifyall method must also be called in a synchronous code block (that is, the calling thread must hold the lock on the object), and their function is this:

ladies and gentlemen. Gentlemen, please note that the object of the lock I am about to run out, please wake up and prepare. Immediately you will be able to use the lock.

The difference is. The Notify method simply wakes up a waiting thread (as far as waking who, unsure!). )。 The Notifyall method wakes up all the threads that are waiting.

Another point of particular emphasis: after invoking the Notify and Notifyall methods, the current thread does not immediately discard the lock's ownership, but must wait until the current synchronization block has finished running before the lock is conceded.

Assuming that an object did not call the wait method before, the call to the Notify method has no effect whatsoever.

Consider the following example:

Package Com.cooperation;import Java.util.concurrent.timeunit;public class test{public static Object object = New Objec    T (); Static Class Thread1 implements Runnable {@Override public void run () {synchronized (O                bject) {System.out.println (Thread.CurrentThread (). GetName () + "is running.");                try {object.wait ();                } catch (Interruptedexception e) {e.printstacktrace ();    } System.out.println (Thread.CurrentThread (). GetName () + "Get the lock.");}} Static Class Thread2 implements Runnable {@Override public void run () {synchronized (O                bject) {System.out.println (Thread.CurrentThread (). GetName () + "is running.");                Object.notify (); System.out.println (Thread.CurrentThread (). GetnamE () + "Invoke notify ()");    System.out.println (Thread.CurrentThread (). GetName () + "release the Lock.");}}         public static void Main (string[] args) throws Interruptedexception {thread thread1 = new Thread (new Thread1 ());        Thread thread2 = new Thread (new Thread2 ());        Thread1.start ();        TimeUnit.SECONDS.sleep (1);    Thread2.start (); }}
Run results (run multiple times with the same result):
Thread-0 is running. Thread-1 is running. Thread-1 invoke Notify () Thread-1 release the lock. Thread-0 get the lock.

You can see that the object lock is released when Thread-0 calls the Wait method. Thread-1 acquires the lock and calls notify's release lock, but this time the thread does not immediately acquire an object lock. Instead, it waits until the Thread-1 synchronization block exits before acquiring the lock of object.

Assume the System.out.println (Thread.CurrentThread (). GetName () + "Release the Lock" in class Thread2. This sentence is placed outside of synchronized (object). It is possible to run results such as the following:

Thread-0 is running. Thread-1 is running. Thread-1 invoke notify () Thread-0 get the lock. Thread-1 Release the lock.

This is because when Thread-1 releases the object lock and exits the synchronization block, Thread-0 acquires the lock immediately, and the order of the two-thread print statements is random.

A condition class appears after JDK1.4, and this class also implements the same functionality. It is also generally recommended to use condition instead of the Wait,notify,notifyall family to achieve more secure inter-thread collaboration communication, such as arrayblockingqueue using condition for blocking queues.

This I will be involved in the future blog.

If you have any comments or suggestions, please leave a comment below.



Java Inter-threading collaboration: WAIT.NOTIFY.NOTIFYALL

Related Article

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.