The wait-and-wake mechanism involves methods:
Wait (): The thread is frozen and the wait thread is stored in the thread pool.
NOTICFY (): Wakes up one thread in the same thread pool (any thread that may also be the current wait)
Notifyall (): Wakes all threads in the same thread pool.
These methods must be defined in synchronization, because this method is used to manipulate the thread state, and it must be clear which locked thread to operate on.
Why Wait,notify,notifyall is defined in the object class as a method of manipulating threads.
Because these methods are the monitor (lock) method, the monitor is a lock.
A lock is an arbitrary object, and the method called by any object is in the object class.
Class resource{
private String name;
Private String sex;
Private Boolean flag = false;
Public synchronized void Set (string name, string sex) {
if (flag) {
Try{wait ();} catch (Exception e) {}
}
Notify ();
THIS.name = name;
This.sex = sex;
System.out.println (this.name+ "**input*" +this.sex);
Flag = true;
}
Public synchronized void out () {
if (!flag) {
Try{wait ();} catch (Exception e) {}
}
Notify ();
System.out.println (this.name+ "**output*" +this.sex);
Flag = false;
}
}
Class Input implements Runnable {
Resource s;
Input (Resource t) {
THIS.S = t;
}
int i = 0;
public void Run () {
while (true) {
if (i ==0) {
S.set ("Mike", "Man");
}else{
S.set ("Xixi", "women");
}
i= (i+1)% 2;
}
}
}
Class Output implements runnable{
Resource s;
Output (Resource t) {
THIS.S = t;
}
public void Run () {
while (true) {
S.out ();
}
}
}
Class resourcedemo{
public static void Main (string[] arg) {
Resource s = new Resource ();
Input p = new input (s);
Output o = new output (s);
thread T1 = new Thread (p);
Thread t2 = new Thread (o);
T1.start ();
T2.start ();
}
}
Java Multithreading (thread communication-waiting for a new mechanism-code optimization)