这3个都是Object的方法,用于线程间的同步。
使用起来很简单。
执行这3个方法都需要先获得监视器的锁。否则会报异常。
在一个线程的锁被notify后,除非它再次获得lock,否则不会执行。
public class Object_Wait_Notify {
private static Object SYNC_OBJECT = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("t1 is running");
synchronized (SYNC_OBJECT){
System.out.println("t1 got the lock");
try {
Thread.sleep(200);
System.out.println("t1 will wait and release the lock");
SYNC_OBJECT.wait();
System.out.println("t1 got the monitor again");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("t1 will over");
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("t2 is running");
synchronized (SYNC_OBJECT){
System.out.println("t2 got the lock and run");
System.out.println("t2 notify t1,but t1 will not run unless it got the lock");
SYNC_OBJECT.notify();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t2 release the lock");
}
System.out.println("t2 will over");
}
});
t2.start();
}
}
输出:
t1 is running
t1 got the lock
t2 is running
t1 will wait and release the lock
t2 got the lock and run
t2 notify t1,but t1 will not run unless it got the lock
t2 release the lock
t2 will over
t1 got the monitor again
t1 will over