Java Basic Tutorials Java thread Waiting with Java Wake thread Java multithreaded tutorial _java

Source: Internet
Author: User
Tags static class thread class

In this chapter, the thread wait/wake method is introduced. The topics involved include:
1. Wait (), notify (), Notifyall () and other methods introduced
2. Wait () and notify ()
3. Wait (long Timeout) and notify ()
4. Wait () and Notifyall ()
5. Why notify (), wait (), and other functions are defined in object, not in thread

Wait (), notify (), Notifyall () and other methods introduced
In Object.java, interfaces such as Wait (), notify (), and notifyall () are defined. The function of Wait () is to let the current thread into the waiting state, while the () will also let the current thread release the lock it holds. The role of Notify () and Notifyall () is to wake up the waiting thread on the current object, notify () is to wake up a single thread, and Notifyall () is to wake up all the threads.

The API details about wait/wake in the object class are as follows:
Notify ()--wakes up a single thread waiting on this object monitor.
Notifyall ()--wakes up all threads waiting on this object monitor.
Wait ()--leave the current thread in "Waiting (blocking) state" until another thread calls the object's notify () method or Notifyall () method, and the current thread is awakened (enters the Ready state ").
Wait (long timeout)--keeps the current thread in the waiting (blocking) state until the other thread calls the object's notify () method or Notifyall () method, or exceeds the specified amount of time ", the current thread is awakened (into into the ready state).
Wait (long timeout, int nanos)--Leave the current thread in "Waiting (blocking) state" until another thread calls the object's notify () method or Notifyall () method, or some other thread interrupts the current thread. Or has exceeded a certain amount of actual time, the current thread is awakened (into the ready state).


2. Wait () and notify () examples
The following example shows a scenario where wait () and notify () are used together.

Copy Code code as follows:

Waittest.java's source code
Class Threada extends thread{

Public Threada (String name) {
Super (name);
}

public void Run () {
Synchronized (this) {
System.out.println (Thread.CurrentThread (). GetName () + "Call Notify ()");
Wakes up the current wait thread
Notify ();
}
}
}

public class Waittest {

public static void Main (string[] args) {

Threada T1 = new Threada ("T1");

Synchronized (t1) {
try {
Start the thread T1
System.out.println (Thread.CurrentThread (). GetName () + "start T1");
T1.start ();

The main thread waits for T1 to be awakened by notify ().
System.out.println (Thread.CurrentThread (). GetName () + "Wait ()");
T1.wait ();

System.out.println (Thread.CurrentThread (). GetName () + "continue");
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}

Run Result:

Copy Code code as follows:

Main start T1
Main Wait ()
T1 Call Notify ()
Main continue

Results show:
The following figure illustrates the process of "main thread" and "Thread T1".

(01) Note that the "main thread" in the figure represents "main thread main". Thread T1 represents the thread T1 that is started in waittest. and "lock" represents "T1 this object's Sync lock".
(02) The "Main thread" creates a new "threading T1" through the new Threada ("T1"). The "T1 object's Sync lock" is then obtained via synchronized (T1). Then call T1.start () to start the thread t1.
(03) The "main thread" executes t1.wait () to release the "lock of the T1 object" and enter the "wait (blocking) state". Wait for the thread on the T1 object to wake it up by notify () or Notifyall ().
(04) after "Thread T1" is run, get "lock of current Object" by synchronized (this), then invoke notify () to wake up "wait thread on current object", that is, wake "main thread".
(05) After the "thread T1" has finished running, release the "lock of the current object." Next, the main thread gets the lock of the T1 object and then runs.


For the above code? Once a friend asked: T1.wait () should be let "thread T1" wait, but, why is the "main thread main" wait?
Before we answer this question, let's look at a brief introduction to wait in the JDK documentation:

Copy Code code as follows:

Causes the "current thread" until another thread invokes the Notify () method and the Notifyall () method for this Obje Ct.
In the "other words", this is behaves exactly as if it simply performs the call Wait (0).
The current thread must own this object monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting in this object ' s Mon Itor to wake up either through a call to the Notify method or the Notifyall method. The thread then waits until it can re-obtain ownership to the monitor and resumes execution.

The Chinese meaning is probably:

Causes the current thread to wait until another thread calls notify () or Notifyall () to wake the thread. In other words, this method is the same as the effect of Wait (0)! (Add, for a wait (long Millis) method, when the Millis is 0 o'clock, the infinity waits until it is awakened by notify () or Notifyall ().
The current thread must have a synchronized lock on the object when calling Wait (). After the thread calls wait (), it releases the lock, and waits until the Notify () or Notifyall () method of the synchronization lock of the object is called by the other thread. The thread then continues to wait until it retrieves the synchronized lock for the object, and then it can then run.
Note: In the JDK's interpretation, the effect of Wait () is to keep the current thread waiting, and "current thread" is the thread that is running on the CPU!
This also means that although t1.wait () is a wait () method called by thread T1, the place where t1.wait () is invoked is in "main thread main". The main thread must be "current thread", which is the running state, before t1.wait () can be executed. So, at this point, the current thread is the main thread main! Therefore, t1.wait () is to let "main thread" wait, not "thread T1"!


3. Wait (long Timeout) and notify ()
Wait (long timeout) makes the current thread "waiting (blocking) state" until the other thread calls the object's notify () method or Notifyall () method, or exceeds the specified amount of time, and the current thread is awakened (into the ready state).
The following example is a scenario where a thread is awakened when a wait (long timeout) is timed out.

Copy Code code as follows:

Waittimeouttest.java's source code
Class Threada extends thread{

Public Threada (String name) {
Super (name);
}

public void Run () {
System.out.println (Thread.CurrentThread (). GetName () + "Run");
Dead loops, running constantly.
while (true)

}
}

public class Waittimeouttest {

public static void Main (string[] args) {

Threada T1 = new Threada ("T1");

Synchronized (t1) {
try {
Start the thread T1
System.out.println (Thread.CurrentThread (). GetName () + "start T1");
T1.start ();

The main thread waits for the T1 to wake up by notify () or Notifyall (), or over 3000ms delay, before being awakened.
System.out.println (Thread.CurrentThread (). GetName () + "call Wait");
T1.wait (3000);

System.out.println (Thread.CurrentThread (). GetName () + "continue");
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}

Run Result:

Copy Code code as follows:

Main start T1
Main call Wait
T1 run//approximately 3 seconds later ... Output "main Continue"
Main continue

Results show:
The following figure illustrates the process of "main thread" and "Thread T1".
(01) Note that the "main thread" in the figure represents the Waittimeouttest main thread (that is, the thread main). Thread T1 represents the thread T1 that is started in waittest. and "lock" represents "T1 this object's Sync lock".
(02) Main thread main execution T1.start () starts "Thread T1".
(03) Main thread main execution t1.wait (3000), at this point, the main thread into the "blocking state." If the thread used to T1 object locks is awakened by notify () or Notifyall () or after "timeout 3000ms", the main thread main enters the ready state before it can be run.
(04) "Thread T1" after running, into the dead loop, has been running continuously.
(05) After the timeout of 3000ms, the main thread main goes to the ready state and then goes to "Run state."

4. Wait () and Notifyall ()
From the previous example, we know that notify () can wake up a single thread waiting on this object monitor.
Below, we illustrate the use of Notifyall () by example, which is to wake up all threads waiting on this object monitor.

Copy Code code as follows:

public class Notifyalltest {

private static Object obj = new Object ();
public static void Main (string[] args) {

Threada T1 = new Threada ("T1");
Threada t2 = new Threada ("T2");
Threada t3 = new Threada ("T3");
T1.start ();
T2.start ();
T3.start ();

try {
System.out.println (Thread.CurrentThread (). GetName () + "sleep (3000)");
Thread.Sleep (3000);
catch (Interruptedexception e) {
E.printstacktrace ();
}

Synchronized (obj) {
The main thread waits for awakening.
System.out.println (Thread.CurrentThread (). GetName () + "Notifyall ()");
Obj.notifyall ();
}
}

Static class Threada extends thread{

Public Threada (String name) {
Super (name);
}

public void Run () {
Synchronized (obj) {
try {
Print output results
System.out.println (Thread.CurrentThread (). GetName () + "Wait");

Wakes up the current wait thread
Obj.wait ();

Print output results
System.out.println (Thread.CurrentThread (). GetName () + "continue");
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}
}

Run Result:

Copy Code code as follows:

T1 wait
Main Sleep (3000)
T3 Wait
T2 wait
Main Notifyall ()
T2 continue
T3 continue
T1 continue

Results show:
Refer to the flowchart below.
(01) New and 3 Threads "T1", "T2" and "T3" are started in the main thread.
(02) The main thread sleeps 3 seconds through sleep (3000). While the main thread sleeps for 3 seconds, we assume that the 3 threads "T1", "T2" and "T3" are running. Take "T1" as an example, when it runs, it executes obj.wait () waits for other threads to wake it up by notify () or amount nofityall (), the same reason that "T2" and "T3" also wait for other threads to pass through nofity () or Nofityall () To awaken them.
(03) The main thread sleeps after 3 seconds, then runs. The execution Obj.notifyall () wakes up the wait threads on obj, that is, the 3 threads that wake up "T1", "T2" and "T3". Immediately after the main thread's synchronized (obj) runs, the main thread releases the obj lock. In this way, "T1", "T2" and "T3" can get "obj lock" and continue to run!




5. Why notify (), wait (), and other functions are defined in object, not in thread
The wait () in object, notify (), and the like synchronized, operate on the synchronized lock of the object.

Waiting () causes the current thread to wait because the thread is in the waiting state, so the thread should release the "Sync Lock" it holds, otherwise the other thread will not get the "sync lock" to run!
OK, after the thread calls wait (), it releases the "Sync lock" it holds, and, according to the previous introduction, we know that the waiting thread can be awakened by notify () or Notifyall (). Now, consider a question: what does notify () wake up to wait for threads on? Or, what is the connection between wait () waiting thread and notify ()? The answer is: "Synchronize locks on objects."

The thread that is responsible for waking the waiting thread (which we call the "wake-up thread"), it can wake up the wait thread only after obtaining the "sync Lock for this object" (where the sync lock must be the same as the waiting thread's sync lock) and calling the Notify () or Notifyall () method. Although the wait thread is awakened, it cannot be executed immediately because the wake thread also holds "synchronized locks on the object." You must wait until the wake thread frees the object's sync lock before the waiting thread can get to the object's sync lock to continue running.

In short, notify (), wait () depends on the "sync lock", while the "Sync Lock" is held by the object lock, and each object has and has only one! This is why the functions such as notify (), wait () are defined in the object class, not the thread class.

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.