wait() 和 sleep() 的区别
- 来自不同的类:前者是 Object类,后者是Thread类
- 是否会释放锁:前者会释放锁,后者不会释放锁
- 使用的范围:前者必须在
同步代码块
中,后者任意
wait() 和 notifyAll()
等待和唤醒:方法必须在 同步代码块
中,monitor.wait()
@Test
public void test() {
Object obj = new Object();
new Thread(()->{
synchronized (obj) {
try {
System.out.println(Thread.currentThread().getName() + " 小j还没来,我等他一会吧");
obj.wait();
System.out.println(Thread.currentThread().getName() + " 哈喽~ 我们走吧");
} catch (Exception e) {
e.printStackTrace();
}
}
}, "thread-1").start();
new Thread(()->{
// 模拟 thread-1 先到(先拿到锁)
try { Thread.sleep(2000); } catch (Exception e) { } finally {}
synchronized (obj) {
System.out.println(Thread.currentThread().getName() + " 哈喽~");
obj.notifyAll();
System.out.println(Thread.currentThread().getName() + " 久等了,朋友,辛苦辛苦!");
}
}, "thread-2").start();
try { Thread.sleep(5000); } catch (Exception e) { } finally {}
}