Java------Multithreading: waiting for wake-up mechanism

Source: Internet
Author: User

Class Res {String name; String sex;} Class input implements Runnable {private Res r;public Input (Res R) {//TODO auto-generated constructor STUBTHIS.R = r;} public void Run () {int x = 0;while (True) {synchronized (R) {if (x = = 0) {r.name = "Mike", R.sex = "man";} else {r.name = " Lili "; r.sex =" female female ";} x = ++x% 2;}}} Class output implements Runnable {private Res r;object obj = new Object (); output (Res r) {THIS.R = R;} public void Run () {while (true) {synchronized (R) {System.out.println (r.name + "----" + R.sex);}}} public class Communicate {public static void main (string[] args) {//TODO auto-generated method Stubres r = new Res (); Inpu T in = new Input (r), output out = new output (r); thread T1 = new thread (in); Thread t2 = new Thread (out); T1.start (); T2.start ();}}


This is an example of the communication between multithreading in the previous article, but the result of this example is this:

Lili----Female Girl

Lili----Female Girl

Lili----Female Girl

Lili----Female Girl

Lili----Female Girl

Lili----Female Girl

Lili----Female Girl

Mike----Man

Mike----Man

Mike----Man

Mike----Man

This is the case. Let's talk about how this happens:

In this example, there are two threads that implement input and output functions, respectively. At some point the input thread gets the CPU execution time, it will not stop the input, constantly update the RES content, the same, when the output of the thread gets execution, it will not stop printing the current res content, so there is this situation.

Now we want them to alternate the printing, that is to say:

Lili----Female Girl

Mike----Man

Lili----Female Girl

Mike----Man

Lili----Female Girl

Mike----Man

This uses a multi-threaded wait-wake mechanism, in which the so-called wait-wake mechanism is actually the wait () method and the Notify () method, which causes the current thread to wait to discard the execution qualification and wake-up thread.

-------------------------API-----------------------------------

wait

Public final void Wait (long timeout) throws interruptedexception

Causes the current thread to wait before another thread calls this object's notify () method or the Notifyall () method, or exceeds the specified amount of time.

The current thread must have this object monitor.

This method causes the current thread (called T) to place itself in the object's wait set, and then discards all synchronization requirements on the object. For thread scheduling purposes, thread T is disabled and dormant until one of the following four scenarios occurs:

· One of the other threads calls the Notify method of this object, and the thread T happens to be selected as the thread that is awakened.

· One of the other threads calls the Notifyall method of this object.

· One of the other threads interrupts the thread T.

· The actual time specified has been reached. However, if timeout is zero, the actual time is not considered and the thread waits until the notification is received.

Then, the thread T is removed from the object's waiting set and the thread is dispatched again. The thread then competes with other threads in a normal way to gain the right to synchronize on that object, and once control of the object is obtained, all its synchronous declarations on that object are restored to the previous state, which is the case when the wait method is called. Then, the thread T is returned from the call of the wait method. Therefore, when returning from the wait method, the synchronization state of the object and thread T is exactly the same as when the wait method is called.

The thread can also wake up with a so-called spurious wakeup (spurious wakeup) without being notified, interrupted, or timed out. Although this situation rarely occurs in practice, the application must prevent it from occurring by testing the condition that should cause the thread to be alerted, and then continue waiting if the condition is not met. In other words, the wait should always occur in the loop, as in the following example:

Synchronized (obj) {while (<condition does not hold>) obj.wait (timeout), ...//Perform action appropriate to Conditio n}

(For more information on this topic, see 3rd. 2.3 or Addison-wesley B in the Concurrent programming in Java (Second Edition) (Joshua, 2000) written by Doug Lea The 50th item in the effective Java Programming Language Guide (Addison-wesley, 2001), written by Loch.

Interruptedexception is thrown if the current thread is interrupted by any thread before it waits or waits. This exception is thrown when the lock state of this object is resumed as described above.

Note that because the wait method places the current thread in the object's waiting set, it can only unlock the object, and any other objects that can synchronize the current thread are still locked while the threads are waiting.

This method should be called only by threads that are the owner of this object monitor. For a description of the method that the thread can be the owner of the Monitor, see the Notify method.

Parameters:

Timeout-The maximum time, in milliseconds, to wait.

Thrown:

illegalargumentexception -If the timeout value is negative.

illegalmonitorstateexception -If the current thread is not the owner of this object monitor.

interruptedexception -If any thread interrupts the current thread before the current thread waits for notification or while it is waiting for notification. When this exception is thrown, the interrupt state of the current thread is cleared.

Notify

Public final void 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.

Until the current thread discards the lock on this object, it can continue to execute the awakened thread. The awakened thread competes with all other threads that are actively synchronizing on the object, for example, the thread that wakes up does not have a reliable privilege or disadvantage as the next thread that locks the object.

This method should be called only by threads that are the owner of this object monitor. A thread can be the owner of this object monitor by one of the following three methods:

· By executing the synchronous instance method of this object.

· The body of the synchronized statement that is synchronized by executing on this object.

· For objects of class type, you can do this by executing a synchronous static method of the class.

Only one thread can have a monitor for an object at a time.

Thrown:

illegalmonitorstateexception -If the current thread is not the object Monitor's

------------------------------------------------------------------------

Notify () can only wake up one thread at a time, if there are multiple threads, the first waiting thread is awakened.

Notifyall () wakes all threads.


Class Res {String name; String Sex;boolean flag = false;} Class input implements Runnable {private Res r;public Input (Res R) {//TODO auto-generated constructor STUBTHIS.R = r;} public void Run () {int x = 0;while (True) {synchronized (R) {if (R.flag = = true) try {r.wait ();} catch (Interruptedexceptio n e) {//TODO auto-generated catch Blocke.printstacktrace ();} if (x = = 0) {r.name = "Mike"; r.sex = "man";} else {r.name = "Lili"; r.sex = "female female";} x = ++x% 2;r.flag = True;r.notify ();}}} Class Output implements Runnable {private Res r;output (Res r) {THIS.R = R;} public void Run () {if (true) {synchronized (R) {if (R.flag = = false) try {r.wait ();} catch (Interruptedexception e) {// TODO auto-generated catch Blocke.printstacktrace ();} System.out.println (r.name + "----" + r.sex); R.flag = False;r.notify ();}}} public class Communicate {public static void main (string[] args) {//TODO auto-generated method Stubres r = new Res (); Inpu T in = new Input (r), output out = new output (r); thread T1 = new thread (in); ThRead T2 = new Thread (out); T1.start (); T2.start ();}} 


Printing results:

Lili----Female Girl
Mike----Man
Lili----Female Girl
Mike----Man
Lili----Female Girl
Mike----Man



Java------Multithreading: waiting for wake-up mechanism

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.