基本差别
- sleep是Thread类的方法,wait是Object类中定义的方法
- sleep方法可以在任何的地方使用
- wait方法只能在sychronized方法或synchronized块中使用
最主要的本质区别
- Thread.sleep()只会让出CPU,不会导致锁行为的改变
- Object.wait()不仅会让出CPU,还会释放已经占有的同步资源
代码演示
示例1
public class CycleWait implements Runnable{
private String value;
@Override
public void run() {
try{
Thread.sleep(5000);
}catch (InterruptedException e){
e.printStackTrace();
}
value = "We have data now";
}
public static void main(String[] args) throws InterruptedException {
CycleWait cycleWait = new CycleWait();
Thread t = new Thread(cycleWait);
t.start();
System.out.println("Value : " + cycleWait.value);
//主线程的等待方
while (cycleWait.value == null){
Thread.sleep(100);
}
System.out.println("Value : " + cycleWait.value);
}
}
运行结果
Value : null
Value : We have data now
Value在线程t休眠5秒之后才完成赋值操作
示例2
package com.mmall.concurrency.thread;
public class WaitSleepDemo {
public static void main(String[] args) {
final Object lock = new Object();
new Thread(() -> {
try {
System.out.println("Thread A is waiting to get lock");
synchronized (lock){
System.out.println("Thread A get lock");
Thread.sleep(20);
System.out.println("Thread A do wait method ");
//线程A释放锁
lock.wait();
System.out.println("Thread A is done ---");
}
}catch (InterruptedException e ){
e.printStackTrace();
}
}).start();
//设置成2000,线程A的wait操作释放锁之后,主线程等待,并没有进入线程B,这个时候还是线程A先完成工作
try{
Thread.sleep(20);
}catch (InterruptedException e){
e.printStackTrace();
}
new Thread(() -> {
try {
System.out.println("Thread B is waiting to get lock");
synchronized (lock){
System.out.println("Thread B get lock");
Thread.sleep(20);
lock.notifyAll();
System.out.println("Thread B is done ---");
}
}catch (InterruptedException e ){
e.printStackTrace();
}
}).start();
}
}
关于notify
运行结果
Thread A is waiting to get lock
Thread A get lock
Thread A do wait method
Thread B is waiting to get lock
Thread B get lock
Thread B is done ---
Thread A is done ---
网友评论