wait是让使用wait方法的对象等待,暂时先把对象锁给让出来,给其它持有该锁的对象用,其它对象用完后再告知(notify)等待的那个对象可以继续执行了,因此,只有在synchronized块中才有意义(否则,如果大家并不遵循同步机制,那还等谁呢?根本没人排队,也就谈不上等待和唤醒了)
以下是一个例子,用以展示这种机制:
public class ThreadA {
public static void main(String[] args) {
ThreadB b = new ThreadB();
//主线程中启动另外一个线程
b.start();
synchronized(b) {
try {
System.out.println("Waiting for b to complet...");
b.wait();
System.out.println("ThreadB is Completed.Now back to main");
}catch(InterruptedException e) {
}
}
System.out.println("Total is :"+b.total);
}
}
class ThreadB extends Thread{
int total;
public void run() {
synchronized(this) {
System.out.println("ThreadB is running..");
for(int i =0;i<=100;i++) {
total +=i;
}
System.out.println("total is"+total);
notify();
}
}
}
运行结果: