package threadcoreknowledge.threadobjectclasscommonmethods;
/** 展示wait和notify的基本用法
* 1.研究代码的执行顺序
* 2.证明wait释放锁
* @author Just Happy
*/
public class Wait {
public static Object object = new Object();
static class Thread1 extends Thread{
@Override
public void run() {
synchronized (object){
System.out.println("线程"+Thread.currentThread().getName()+"开始执行了");
try {
//释放锁
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程"+Thread.currentThread().getName()+"获得了锁");
}
}
}
static class Thread2 extends Thread{
@Override
public void run() {
synchronized (object){
// notify不会立刻释放锁,会把代码块执行完
object.notify();
System.out.println("线程"+Thread.currentThread().getName()+"调用了notify()");
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread1 thread1 = new Thread1();
Thread1 thread2 = new Thread1();
Thread2 thread3 = new Thread2();
thread1.start();
Thread.sleep(300);
thread2.start();
Thread.sleep(300);
thread3.start();
}
}
实验结果:
我的理解是Thread1的两个实例只有一个会获得锁,但是为什么好像一开始都打印出那句话了,synchronzied关键字的范围怎么变小了啊?