1) wait、 notify、 notifyAll
这单个方法是属于Object类的方法
wait: 导致当前的线程等待,直到其他线程调用此对象的notify()方法或notifyAll()方法
notify: 唤醒在此对象监视器等待的一个线程
notifyAll: 唤醒在此对象监视器上等待的所有线程
2) demo
public class TestWait3 {
public static void main(String[] args) {
final Object obj = new Object();
Thread t1 = new Thread() {
public void run() {
synchronized (obj) {
System.out.println("t1 start");
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t1 end");
}
}
};
Thread t2 = new Thread() {
public void run() {
synchronized (obj) {
System.out.println("t2 start");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
obj.notify();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t2 end");
}
}
};
t1.start();
t2.start();
}
public void m() {
System.out.println("m1");
}
}
t2.notify()之后会释放锁,但是会继续执行t2后,才会执行得到锁的t1;wait会让出cpu,而notify不会让,notify重在通知使用obj的对象“用完了”,wait重在通知其他同一个obj的线程“我暂时不用了”并且让出cpu