wait()、notify()、notifyAll()是三个定义在Object类里的方法,可以用来控制线程的状态。
这三个方法最终调用的都是jvm级的native方法。随着jvm运行平台的不同可能有些许差异。
如果对象调用了wait方法就会使持有该对象的线程把该对象的控制权交出去,然后处于等待状态。
如果对象调用了notify方法就会通知某个正在等待这个对象的控制权的线程可以继续运行。
如果对象调用了notifyAll方法就会通知所有等待这个对象控制权的线程继续运行。
注意:一定要在线程同步中使用,并且是同一个锁的资源
class Res {
public String userSex;
public String userName;
//线程通讯标识
public boolean flag = false;
}
class IntThrad extends Thread {
private Res res;
public IntThrad(Res res) {
this.res = res;
}
@Override
public void run() {
int count = 0;
while (true) {
synchronized (res) {
if (res.flag) {
try {
// 当前线程变为等待,但是可以释放锁
res.wait();
} catch (Exception e) {
}
}
if (count == 0) {
res.userName = "余胜军";
res.userSex = "男";
} else {
res.userName = "小紅";
res.userSex = "女";
}
count = (count + 1) % 2;
res.flag = true;
// 唤醒当前线程
res.notify();
}
}
}
}
class OutThread extends Thread {
private Res res;
public OutThread(Res res) {
this.res = res;
}
@Override
public void run() {
while (true) {
synchronized (res) {
if (!res.flag) {
try {
res.wait();
} catch (Exception e) {
// TODO: handle exception
}
}
System.out.println(res.userName + "--" + res.userSex);
res.flag = false;
res.notify();
}
}
}
}
public class ThreaCommun {
public static void main(String[] args) {
Res res = new Res();
IntThrad intThrad = new IntThrad(res);
OutThread outThread = new OutThread(res);
intThrad.start();
outThread.start();
}
}