多线程之间需要协调工作:如果条件不满足,则等待;当条件满足时,等待该条件的线程将被唤醒。在Java中,这个机制的实现依赖于wait/notify。等待机制与锁机制是密切关联的 wait():
等待对象的同步锁,需要获得该对象的同步锁才可以调用这个方法,否则编译可以通过,但运行时会收到一个异常:IllegalMonitorStateException。
调用任意对象的 wait() 方法导致该线程阻塞,该线程不可继续执行,并且该对象上的锁被释放。 notify():
唤醒在等待该对象同步锁的线程(只唤醒一个,如果有多个在等待),注意的是在调用此方法的时候,并不能确切的唤醒某一个等待状态的线程,而是由JVM确定唤醒哪个线程,而且不是按优先级。
调用任意对象的notify()方法则导致因调用该对象的 wait()方法而阻塞的线程中随机选择的一个解除阻塞(但要等到获得锁后才真正可执行) notifyAll():
唤醒所有等待的线程,注意唤醒的是notify之前wait的线程,对于notify之后的wait线程是没有效果的 wait(),notify(),notifyAll()不属于Thread类,而是属于Object基础类,也就是说每个对像都有wait(),notify(),notifyAll()的功能。因为都个对像都有锁,锁是每个对像的基础,当然操作锁的方法也是最基础了。
package com.Thread.Demo2;
public class ThreadTest {
public static void main (String[] args) {
ResourcesDemo r = new ResourcesDemo();
Input in =new Input(r);
Output out = new Output(r);
Thread tin = new Thread(in );
Thread tout = new Thread(out );
tin.start();
tout.start();
}
}
package com.Thread.Demo2;
public class ResourcesDemo {
public String name;
public String sex;
public boolean flag=false ;
}
package com.Thread.Demo2;
public class Output implements Runnable {
private ResourcesDemo r;
public Output (ResourcesDemo r) {
this .r=r;
}
public void run ()
{
while (true )
{
synchronized (r) {
if (!r.flag)
{
try {r.wait();}
catch (Exception e) {}
}
System.out.println(r.name+" " +r.sex);
r.flag=false ;
r.notify();
}
}
}
}
package com.Thread.Demo2;
import javax.annotation.Resource;
public class Input implements Runnable {
private ResourcesDemo r;
public Input (ResourcesDemo r) {
this .r=r;
}
public void run ()
{
int i =0 ;
while (true )
{
synchronized (r)
{
if (r.flag) {
try {
r.wait();
}catch (Exception e){
}
}
if (i%2 ==0 ) {
r.name="张三" ;
r.sex="男" ;
}else {
r.name = "lisi" ;
r.sex = "nv" ;
}
r.flag=true ;
r.notify();
}
i++;
}
}
}