区别
sleep
- sleep是Thread类的静态方法随时调用
- sleep在调用时不会释放所持有的锁
wait
- wait是对象的方法
- wait会释放锁
- 在调用notify唤醒wait时候,notify作用域必须持有在调用wait时候所加的锁
- notify后并不会立即唤醒,等到获得原环境时候有唤醒条件
代码
public class ConcurrentTest {
static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("t1 is waiting to get lock");
synchronized (lock){
System.out.println("t1 get lock");
try { // sleep does not lose lock
System.out.println("t1 sleep start");
Thread.sleep(3000);
System.out.println("t1 sleep end");
System.out.println("t1 wait start");
lock.wait();
System.out.println("t1 wait end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("t2 is waiting to get lock");
synchronized (lock){ // t2将在t1 wait时候获取锁
System.out.println("t2 get lock, t2 attempt to notify t1");
lock.notify();
try {
System.out.println("t2 keep lock, sleep start");
Thread.sleep(3000);
System.out.println("t2 sleep end, release lock");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t1.start();
Thread.sleep(10);
t2.start();
}
}
/**
运行结果:
t1 is waiting to get lock
t1 get lock
t1 sleep start
t2 is waiting to get lock
t1 sleep end
t1 wait start
t2 get lock, t2 attempt to notify t1
t2 keep lock, sleep start
t2 sleep end, release lock
t1 wait end
Process finished with exit code 0
*/