wait() - notify() - notifyAll() 方法:(这些方法只能在同步代码块或同步方法中调用)*
- wait() : 此方法就将当前线程堵塞,并释放同步监视器
- notify() : 执行此方法,会唤醒一个优先级高点的被wait的线程
- notifyAll() :执行此方法,将会唤醒所有被wait的线程
注意:
上面的三个方法时定义在Object中的,使用这些方法,同步代码块中的同步监视器将作为调用这些方法的对象,所以要是使用类.class作为同步监视器,那么在调用上面的三个方法时,要通过类.class进行调用
我们通过例子进行学习,使用两个线程打印1-20,要求交替打印
代码:
public class Thread_Communication {
public static void main(String[] args) {
PrintNum printNum = new PrintNum();
Thread thread1 = new Thread(printNum);
Thread thread2 = new Thread(printNum);
thread1.setName("线程1");
thread2.setName("线程2");
thread1.start();
thread2.start();
}
}
class PrintNum implements Runnable{
static int i=1;
@Override
public void run() {
while(true) {
// synchronized (PrintNum.class)
synchronized (this) { //因为只实例化一个PrintNum对象,符合同步监视器为同一个对象的条件
// PrintNum.class.notify();
notify();
if(i<=20) {
System.out.println(Thread.currentThread().getName()+" 打印了 "+i);
i++;
try {
// PrintNum.class.wait();
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
break;
}
}
}
}
}
结果: