Java Thread Communication uses
Wait notify mate synchronized
When the thread executes wait (), it releases the current lock and then yields the CPU and enters the wait state.
When the Notify/notifyall method is executed, a thread that waits for the lock on the object is awakened, and then continues to execute until the lock is released after execution of the lock-locked area of the Exit object (the synchronized-decorated code block).
The following code:
public class ThreadTest {
Declares a list collection of thread visualizations
public static list<string> List = new arraylist<> ();
public static void Main (string[] args) {
Object lock = new Object ();
thread T1 = new Thread (new Runnable () {
@Override
public void Run () {
Synchronized (lock) {
for (int i = 0; i < i++) {
List.add ("Lenny");
System.out.println (Thread.CurrentThread (). GetName () + "Add new items to List");
if (list.size () = = 5) {
Lock.notify (); Notifies the lock that a suspended thread continues execution after the synchronized block code execution is finished releasing the lock
System.out.println ("Current thread:" + thread.currentthread (). GetName () + ", notification has been given");
}
}
}
}
}, "T1");
Thread t2 = new Thread (new Runnable () {
@Override
public void Run () {
Synchronized (lock) {
if (list.size ()! = 5) {
try {
Lock.wait (); Here thread hangs release lock
SYSTEM.OUT.PRINTLN ("List Length" +list.size ());
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
System.out.println ("Current thread:" + thread.currentthread (). GetName () + ", receive notification");
}
}
}, "T2");
T2.start ();
T1.start ();
}
}
Results of the operation:
Note here that the T2 thread executes first, T1 the thread. If the T1 thread executes first then T2 cannot get lock,t1 notify when the T2 is not notified.
This is a bit of a disadvantage: can not do real-time notification, to make notification, another thread immediately receive notification, need to use the Java.util.concurrent Countdownlatch
Java Thread Communication