这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
本文深入解析Java中Object类的wait()与notify()方法,通过实例展示了如何实现线程间的同步。文章包括方法使用、锁获取、线程等待与唤醒等关键概念,并通过代码实现验证了同步机制的有效性。
1829

被折叠的 条评论
为什么被折叠?



