package com.thread.test; public class SimpleMN { final static Object object = new Object(); public static class T1 extends Thread { @Override public void run() { synchronized (object) { System.out.println(System.currentTimeMillis() + ":T1 start!"); try { System.out.println(System.currentTimeMillis() + ":T1 Wait for Object"); object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(System.currentTimeMillis() + ":T1 end"); } } } public static class T2 extends Thread { @Override public void run() { synchronized (object) { System.out.println(System.currentTimeMillis() + ":T2 start!notify T1"); object.notify(); System.out.println(System.currentTimeMillis() + ":T2 end"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { Thread t1 = new T1(); Thread t2 = new T2(); t1.start(); t2.start(); } }
执行结果如下
1516328141717:T1 start! 1516328141717:T1 Wait for Object 1516328141717:T2 start!notify T1 1516328141717:T2 end 1516328143717:T1 end
上述代码中开启两个线程T1和T2。T1执行了object.wait()方法,注意在执行wait()方法前T1先申请了object的对象锁,因此在执行obect.wati()时,
它是持有object的对象锁的。wait()方法执行后T1进入等待和状态,并示范object对象锁。T2在执行notify()之前也会先获取object对象锁。T1被唤醒后
做的第一件事儿并不是执行后续的代码,而是要尝试获取object的对象锁。为了让是效果更明显,我特意在notify()之后让T2睡眠了2s(仔细看输出结果中的时间戳),这样可以更加
明显的说明T1在得到notify()通知后,还是会先尝试重新获取object对象锁,然以后执行后续代码。