How to use Wait (), notify (), and Notifyall () –java

Source: Internet
Author: User

Java multithreading is a complex issue, especially when multithreaded access to shared resources at any given time requires more attention. Java 5 introduces classes such as the blockingqueue and executors classes that provide an easy-to-use API that avoids some complexity. Using these analogies directly with wait () and notify () synchronizes the programmer to feel more confident. I also recommend using these new APIs for synchronization, but many times we need old ways, such as maintaining legacy code, for a variety of reasons. In these cases, familiarity with these methods will help you understand. In this tutorial, I discuss some of the concepts of Wait (), notify (), and Notifyall ().

What is the Wait (), notify (), and Notifyall () methods?

Before entering the concept, let's write down the basic definitions of these methods.
In Java, the object class has three final methods that allow threads to understand the locking state of resources, which are:

1.wait ():

Causes the current thread to wait before another thread calls this object's notify () method or the Notifyall () method. In other words, this method behaves as if it were only executing wait (0) calls.
The current thread must have this object monitor. The thread releases ownership of this monitor and waits until other threads wake up by calling the Notify method, or the Notifyall method notifies the thread waiting on this object's monitor. The thread then waits to regain ownership of the monitor before it can continue execution.
It tells the calling thread to discard the lock. We cannot implement the wait () method with pure Java: It is a native method.
It is used to cause a thread to wait for a condition , which must be called within the synchronization area, which locks the object on the object that calls the Wait method. You should always use the wait loop mode to call the Wait method, never call the wait method outside of the loop. The loop tests the condition before and after it waits.
Test the condition before waiting, and skip the wait as soon as the condition is established, which is necessary to ensure the activity.
After waiting for test conditions, if the condition is not established, continue to wait, which is necessary to ensure security.
The syntax for general use of the Wait () method is as follows:

synchronized (lockobject) {     while (! condition)    {         lockobject.wait ();    }           // Take the action here;}
2.notify ():

Wakes up a single thread waiting on this object monitor. If all threads are waiting on this object, then one of the threads is chosen to wake up. The choice is arbitrary and occurs when a decision is made on the implementation. The thread waits on the object's monitor by calling one of the wait methods.
wakes a thread that calls wait () on the same object . It should be noted that the call to notify () does not actually give up the lock on the resource. It tells the waiting thread to wake up. However, if you call Notify () on a resource, but the execution of the resource within the synchronization block takes 10 seconds, the thread waits for an additional 10 seconds, the lock on the object is freed, and the thread that is awakened is executed.

The syntax for calling the Notify () method generally is as follows:

synchronized (lockobject) {    //establish_the_condition;      lockobject.notify ();          // Any additional code if needed}
3.notifyall ():

it wakes up all threads that call Wait () on the same object . In most cases, the highest-priority thread will run first, but there is no guarantee. The others are the same as the Notify () method.
The syntax for calling the Notifyall () method generally is as follows:

synchronized (lockobject) {    establish_the_condition;     Lockobject.notifyall ();}

In general, Notifyall should always be called to wake up all the threads that need to be woken up. You may also wake up some other threads, but this does not affect the correctness of the program, and these threads wake up to check the conditions they are waiting for, and if the condition is found to be unsatisfied, they will continue to wait.
So far, we have learned some basic knowledge that you may already know. Let's write a small program that understands how to use these methods to get the expected results.

How to use the Wait (), notify (), and Notifyall () methods

In this exercise, we will use the wait () and notify () methods to solve the problem of producer consumers. To make the program simple and focus on the use of the Wait () and notify () methods, we will only involve a producer and consumer thread.
Other features of the program are:
1) Producer threads produce new resources per second and are placed in Taskqueue.
2) The consumer thread takes 1 seconds to consume resources from the taskqueue.
3) The maximum capacity of Taskqueue is 5, that is, at any given time the maximum can exist 5 resources in Taskqueue.
4) Two threads run indefinitely.

Designing producer Threads

Here are the producer thread codes based on our requirements:

classProducerImplementsrunnable{Private FinalList<integer>Taskqueue; Private Final intmax_capacity;  PublicProducer (list<integer> Sharedqueue,intsize) {       This. Taskqueue =Sharedqueue;  This. Max_capacity =size; } @Override Public voidrun () {intCounter = 0;  while(true)      {         Try{Produce (counter++); }          Catch(Interruptedexception ex) {ex.printstacktrace (); }      }   }    Private voidProduce (intIthrowsinterruptedexception {synchronized(taskqueue) { while(taskqueue.size () = =max_capacity) {System.out.println (' Queue is full ' + thread.currentthread (). GetName () + "is waiting, size:" +taskqueue.size ());         Taskqueue.wait (); } thread.sleep (1000);         Taskqueue.add (i); System.out.println ("Produced:" +i);      Taskqueue.notifyall (); }   }}

1) Here, the produce (counter++) code is written to an infinite loop so that the producer can generate the elements on a regular basis.
2) We have added the wait () method to the general guidelines mentioned in the first section of the produce () method.
3) Once the wait is over, the producer joins an element Taskqueue and then calls the Notifyall () method to wake up the other thread. The consumer is awakened because the last Wait () method was called by the consumer thread (which is why the producer is waiting for the state).
4) If the consumption element is ready, the consumer thread is awakened.
5) Note that all two threads use the sleep () method to simulate time delays in creating and consuming features.

Designing Consumer Threads

Here are the consumer thread codes based on our needs:

classConsumerImplementsrunnable{Private FinalList<integer>Taskqueue;  PublicConsumer (list<integer>sharedqueue) {       This. Taskqueue =Sharedqueue; } @Override Public voidrun () { while(true)      {         Try{consume (); } Catch(Interruptedexception ex) {ex.printstacktrace (); }      }   }    Private voidConsume ()throwsinterruptedexception {synchronized(taskqueue) { while(Taskqueue.isempty ()) {System.out.println (' Queue is empty ' + thread.currentthread (). GetName () + "is waiting, size:" +taskqueue.size ());         Taskqueue.wait (); } thread.sleep (1000); inti = (Integer) taskqueue.remove (0); System.out.println ("Consumed:" +i);      Taskqueue.notifyall (); }   }}

1) Here the consume () code is written in an infinite loop, allowing the consumer to keep the elements in taskqueue whenever it is consumed.
2) Once the wait is over, the consumer removes an element from the Taskqueue and then calls the Notifyall () method to wake up the other thread. Because the last wait () method is called by the producer thread (which is why the producer is waiting for the state), the producer thread receives a notification that is woken up.
3) If the production element is ready, the producer thread gets notified.

Test your application

Now test the producer and consumer threads.

 Public classproducerconsumerexamplewithwaitandnotify{ Public Static voidMain (string[] args) {List<Integer> Taskqueue =NewArraylist<integer>(); intMax_capacity = 5; Thread Tproducer=NewThread (NewProducer (Taskqueue, max_capacity), "Producer"); Thread Tconsumer=NewThread (NewConsumer (Taskqueue), "Consumer");      Tproducer.start ();   Tconsumer.start (); }}

Output:

produced:0

consumed:0

Queue is empty Consumer is waiting, size:0

Produced:1

Produced:2

Consumed:1

Consumed:2

Queue is empty Consumer is waiting, size:0

Produced:3

Produced:4

Consumed:3

Produced:5

Consumed:4

Produced:6

Consumed:5

Consumed:6

Queue is empty Consumer is waiting, size:0

Produced:7

Consumed:7

Queue is empty Consumer is waiting, size:0

I recommend that you change the time spent by producer and consumer threads to different times and examine different outputs in different scenarios.

Wait (), notify () and Notifyall () methods in the interview question when notify () is called, but what happens when there is no thread waiting?

In general, this is not the case in most cases if these methods are used correctly. But if the Notify () method is called, no other thread waits, notify () simply returns and loses the notification .

Because the wait and notification mechanism does not know the condition in which it sends notifications, it assumes that no threads are waiting and the notification is ignored. A thread that later executes the wait () method must wait for the next notification to occur.

Is there a race condition when the Wait () method releases or acquires a lock?

The wait () method is tightly coupled to the lock mechanism. Object locks are not actually freed until the waiting thread is in a state of receiving notifications. This means that it can receive notifications only if the thread state changes, and the lock is saved. This system prevents any competitive conditions from occurring .

Similarly, the system ensures that the object is completely locked before the thread is moved to the wait state.

If a thread receives a notification, is it guaranteed that the condition is set correctly?

Simply put, there is no guarantee that before the wait () method is called, a thread should always test the condition in the case of a synchronous lock. When returned from the Wait () method, the thread should always test the condition to determine if it should wait. This is because another thread can also test the condition and determine that the wait is unnecessary-processing valid data set by the notification thread.

What happens when multiple threads wait for notification? The call Notify () method is actually which thread was awakened?

It depends on many factors. The Java specification does not determine which thread is awakened. At run time, the thread is awakened based on several factors, including the implementation of Java virtual machines and scheduling and timing issues during program execution. Even on a single processor platform, it is not possible to determine how multiple threads are awakened.

Just like the Notify () method, the Notifyall () method does not allow us to decide which thread is awakened: they are all awakened. When all the threads are awakened, a mechanism can be drawn up between the threads to choose which thread should continue, and that or those threads should then call the Wait () method to continue waiting

Does the Notifyall () method actually wake all threads?

It is also not that all waiting threads wake up, but they still need to acquire object locks. Therefore threads cannot run in parallel: they must wait for the object lock to be freed. Only one thread can run at a time.

If there is only one thread to execute, why wake all the threads?

There are several reasons. For example, there may be more than one condition to wait for . Because we have no control over which thread is awakened, the notification can wake up the thread waiting for a completely different state. By waking up all the threads, we can design the program so that the threads decide for themselves what the next thread should do. Another option might be when a producer generates data that meets multiple consumers . Since it is difficult to determine how many consumers can be informed , one option is to inform them all and let the consumer handle it themselves.

Happy Learning!!

How to use Wait (), notify (), and Notifyall () –java

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.