Java Wait (), notify () and Notifyall () using the experience _java

Source: Internet
Author: User
Wait (), notify () and Notifyall () are all java.lang.Object methods:
Wait (): Causes the "current thread" until another thread invokes the Notify () method and the Notifyall () method for T His object.
Notify (): Wakes up a single thread, is, waiting on the This object ' s monitor.
Notifyall (): Wakes up all threads that are waiting on the This object ' s monitor.
These three methods are the underlying mechanisms that the Java language provides to implement inter thread blocking (Blocking) and control in-process scheduling (inter-process communication). Before explaining how to use it, explain two points first:
1. Just as any object in Java can become a lock (lock), any object can become a conditional queue (Condition queue). and the Wait (), notify () and Notifyall () in this object are the inherent (intrinsic) method of this conditional queue.
2. An object's intrinsic lock and its inherent conditional queue are related, and in order to invoke the method of a conditional queue within an object x, you must obtain the lock of the object X. This is because the mechanism of waiting condition and the mechanism of guaranteeing State continuity are closely combined.
(An object's intrinsic lock and its intrinsic condition \ are related:in order to call any of the condition queue met Hods on object x, your must hold the lock on X. This is because the mechanism for waiting for state-based conditions are necessarily tightly bound to the mechanism fo pres Erving State consistency)
According to the two points above, the lock must first be obtained when calling Wait (), notify () or Notifyall (), and the state variable is protected by the lock, and the intrinsic lock object is the same object as the intrinsic conditional queue object. That is, to perform wait,notify on an object, the object must be locked first, and the corresponding state variable is also protected by the object's lock.
Once you know how to use it, let's ask the following questions:
1. Execute wait, notify, what happens when you don't get a lock?
Please look at the code:
Copy Code code as follows:

public static void Main (string[] args) throws Interruptedexception {
Object obj = new Object ();
Obj.wait ();
Obj.notifyall ();
}

Executing the above code throws a Java.lang.IllegalMonitorStateException exception.
2. Execute wait, when notify, do not get the lock of the object?
Please look at the code:
Copy Code code as follows:

public static void Main (string[] args) throws Interruptedexception {
Object obj = new Object ();
Object lock = new Object ();
Synchronized (lock) {
Obj.wait ();
Obj.notifyall ();
}
}

Executes the code, also throws the java.lang.IllegalMonitorStateException exception.
3. Why is it necessary to obtain a lock on the object when executing wait, notify?
This is because, if there are no locks, wait and notify may produce a race condition (Race Condition). Consider the following producer and consumer scenarios:
1.1 Producer inspection conditions (e.g. cache full)-> 1.2 producers must wait
2.1 Consumers consume a unit of cache-> 2.2 reset conditions (such as cache not full)-> 2.3 call Notifyall () Wake producer
The order we want to be: 1.1->1.2->2.1->2.2->2.3
However, in the case of multithreading, the order may be 1.1->2.1->2.2->2.3->1.2. That is to say, the consumer is already notifyall before the producer waits, so the producer will keep waiting.
Therefore, to solve this problem, you must get the lock of the object at wait and notifyall to ensure synchronization.
See below for a simple model of a producer, a consumer, and a unit of caching implemented using wait,notify:
Copy Code code as follows:

public class Queuebuffer {
int n;
Boolean valueset = false;
synchronized int get () {
if (!valueset)
try {
Wait ();
catch (Interruptedexception e) {
SYSTEM.OUT.PRINTLN ("Interruptedexception caught");
}
System.out.println ("Got:" + N);
Valueset = false;
Notify ();
return n;
}
synchronized void put (int n) {
if (Valueset)
try {
Wait ();
catch (Interruptedexception e) {
SYSTEM.OUT.PRINTLN ("Interruptedexception caught");
}
THIS.N = n;
Valueset = true;
System.out.println ("Put:" + N);
Notify ();
}
}

Copy Code code as follows:

public class Producer implements Runnable {
Private Queuebuffer Q;
Producer (Queuebuffer q) {
THIS.Q = q;
New Thread (This, "Producer"). Start ();
}
public void Run () {
int i = 0;
while (true) {
Q.put (i++);
}
}
}

Copy Code code as follows:

public class Consumer implements Runnable {
Private Queuebuffer Q;
Consumer (Queuebuffer q) {
THIS.Q = q;
New Thread (This, "Consumer"). Start ();
}
public void Run () {
while (true) {
Q.get ();
}
}
}

Copy Code code as follows:

public class Main {
public static void Main (string[] args) {
Queuebuffer q = new Queuebuffer ();
New Producer (q);
New Consumer (q);
System.out.println ("Press Control-c to stop");
}
}

So, by throwing illegalmonitorstateexception exceptions at execution time, the JVM ensures that wait, notify, gets the lock on the object, eliminating the hidden race Condition.
Finally to see a problem: Write a multithreaded program, alternating output 1,2,1,2,1,2 ...
Use wait, notify solve:
Copy Code code as follows:

public class Outputthread implements Runnable {
private int num;
Private Object lock;
public outputthread (int num, Object lock) {
Super ();
This.num = num;
This.lock = lock;
}
public void Run () {
try {
while (true) {
Synchronized (lock) {
Lock.notifyall ();
Lock.wait ();
SYSTEM.OUT.PRINTLN (num);
}
}
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
public static void Main (string[] args) {
Final Object lock = new Object ();
Thread thread1 = new Thread (new Outputthread (1,lock));
Thread thread2 = new Thread (new Outputthread (2, lock));
Thread1.start ();
Thread2.start ();
}
}
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.