1、sleep是Thread类的方法,wait是Object类的方法
2、sleep不会释放对象锁,wait会释放锁
3、sleep不需要与synchronized一起使用,wait需要
4、sleep不需要唤醒,wait需要
import java.util.stream.Stream;
public class DifferenceOfWaitAndSleep {
private final static Object LOCK = new Object();
public static void main(String[] args) {
Stream.of("T1", "T2").forEach(name ->
new Thread(name) {
@Override
public void run() {
m2();
}
}.start()
);
}
public static void m1() {
synchronized (LOCK) {
try {
System.out.println("The Thread " + Thread.currentThread().getName() + " enter.");
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void m2() {
synchronized (LOCK) {
try {
System.out.println("The Thread " + Thread.currentThread().getName() + " enter.");
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
来源:oschina
链接:https://my.oschina.net/lvzi98/blog/3158456