sleep()与wait()方法的区别
最近在看汪文君的Thread相关视频,记录下笔记:
- sleep()方法是Thread类的,wait()方法是Object类的;
- wait()方法必须在monitor锁里面使用,而sleep()不需要;
- sleep()方法参数传入休眠的时间(单位毫秒),wait()可以传入休眠时间参数,也可以不传入,不传参时,需要调用monitor锁的notify()或notifyAll(),将其唤醒。
- wait()方法会释放monitor锁,其他的线程可以继续抢到monitor锁。而sleep()仅是休眠,若sleep()是在monitor锁里面使用,将不会释放锁,当前线程在休眠时间结束后,继续往下执行
测试类:
package com.luomouren.thread.chapter1;
public class DifferentOfSleepAndWait {
public final static Object LOCK = new Object();
public static void main(String[] args) {
try {
// sleep是Thread类的,可以直接调用
Thread.sleep(1000L);
DifferentOfSleepAndWait test = new DifferentOfSleepAndWait();
// wait需要在synchronized锁里使用,使用后会释放monitor锁
new Thread(() -> {
test.testWait();
}).start();
new Thread(() -> {
test.testWait();
}).start();
new Thread(() -> {
test.testNotify();
}).start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void testWait(){
synchronized (LOCK){
System.out.println(Thread.currentThread().getName()+"---testWait enter----");
try {
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"---testWait leave----");
}
}
public void testNotify(){
synchronized (LOCK){
System.out.println(Thread.currentThread().getName()+"---testNotify enter----");
LOCK.notifyAll();
System.out.println(Thread.currentThread().getName()+"---testNotify leave----");
}
}
}
运行结果:
Thread-0—testWait enter—-
Thread-1—testWait enter—-
Thread-2—testNotify enter—-
Thread-2—testNotify leave—-
Thread-1—testWait leave—-
Thread-0—testWait leave—-