Java multithreading 8:wait () and notify ()/notifyall ()

Source: Internet
Author: User

Polling

Threads themselves are independent individuals in the operating system, but threads are not independent of each other, because they communicate and collaborate with each other.

Imagine a scene, a thread to do int type variable i cumulative operation, b thread wait I to 10000 to print out I, how to deal with? One way is that the B thread while (i = = 10000), so that there is communication between two threads, B thread constantly through the rotation to detect i = = 10000 this condition.

This allows us to achieve our needs, but it also poses a problem: the CPU wastes the resources of the B-thread polling operation, because the while operation does not release the CPU resources, causing the CPU to continue to make a judgment operation on this thread. It would be nice if you could release the polling time and use it for other threads.

Wait/notify

There are three methods in object objects, wait (), notify (), Notifyall (), and since they are methods in object, each object is naturally there. These two methods are less common if they are not exposed to multiple threads. Here's a look at the top two methods:

1. Wait ()

The role of Wait () is to wait for the thread that is currently executing the code, place the current thread in the pre-execution queue, and stop execution at the code where wait () stops until it is notified or interrupted. before calling Wait (), the thread must obtain a lock on the object, so the Wait () method can only be called in the synchronous method/synchronous code block .

2, Notify ()

The role of Notify () is that if there are multiple threads waiting, the thread planner randomly picks out a wait thread, notifies it notify (), and makes it wait for the object lock to get the object. Note "Wait for object lock on this object", which means that even if a notification is received, the wait thread does not get the object lock immediately and must wait for the thread of the Notify () method to release the lock. as with Wait (), notify () is also called in the synchronous method/synchronous code block .

In summary,Wait () causes the thread to stop running, and notify () causes the thread that stopped running to continue running .

Wait ()/notify () Use example

Look at the code:

Write a main function, the same thread.sleep (3000) is also to ensure that mt0 run first, so as to see the effects of Wait () and notify ():

Look at the results of the operation:

The time between the first and second lines is obviously 3s, indicating that the code is paused after wait () and notify () before the code starts to run.

The wait () method frees the shared resource's lock from the method that called the thread, and then exits from the running state, entering the wait queue until it is awakened again .

The Notify () method randomly wakes a thread waiting for the same shared resource in the queue and causes the thread to exit the wait state and enter a running state

The Notifyall () method allows all threads waiting in the queue to wait for the same shared resource to exit from the waiting state and into a running state

Finally, if the wait () method and the Notify ()/notifyall () method are not called in the synchronous method/synchronization code block, the virtual opportunity throws java.lang.IllegalMonitorStateException, notice.

Wait () Release lock and notify () do not release the lock

In multi-threaded learning, the "lock" is a concern everywhere, and so is wait () and notify (). The wait () method is to release the lock, and write an example to prove it:

If the wait () method does not release the lock, then Thread-1 does not enter the synchronization code block to print, so the proof is complete.

Next, prove the conclusion that the Notify () method does not release the lock:

Write two threads to call 2 methods, respectively:

Look at the results of the operation:

If the Notify () method releases the lock, then Thread.Sleep (5000) must have another thread to enter the synchronization code block after Thread-1 calls the Notify () method, but in fact there is no need to wait until the Thread-1 has finished executing the code. So, the proof is complete.

Interrupt () interrupt wait ()

As previously mentioned, the interrupt () method does not function as a thread break, but rather an interrupt identifier for the threads at the time of the line blocking, indicating that the thread is interrupted. Wait () is a "blocking scenario" and take a look at the example of interrupting wait () with interrupt ():

Notifyall () Wakes all threads

Use the Notifyall () method of the object to wake up all the wait threads under the same monitor, for example:

Write two threads, one thread that calls TestMethod (Object Lock), and one Notifyall () thread:

The main function opens three wait threads and wakes up with a notifyall thread:

Of course, the Order of awakening is not important because notifyall () wakes all the threads that are in the same resource wait, and the order in which they are awakened, as in the order in which the threads start, is random for the virtual machine.

Java multithreading 8:wait () and notify ()/notifyall ()

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.