1.sleep()是Thread类的方法,是native类型的。wait()是Object类中定义的方法,也是native类型的。
2.sleep()方法可以再任何地方使用。wait()方法只能在synchronized或者synchronized块中使用。因为synchronized是用来加锁,wait是用来释放锁。
两者最本质的区别:
(1)Thread.sleep只会让出CPU,不会导致锁行为的改变。
(2)Object.wait不仅会让出CPU,还会释放已经占有的同步资源锁,以便其他正在等待该资源的线程得到该资源进而去运行。
1.下面的代码表示A线程调用了wait()方法后会释放同步资源锁,释放了同步锁之后就可以供其他线程来占有这个同步资源锁。
public class WaitSleepDemo {
public static void main(String[] args) {
final Object lock = new Object();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread A is waiting to get lock");
synchronized(lock){
try {
System.out.println("thread A get lock");
Thread.sleep(20);
System.out.println("thread A do wait method");
lock.wait(1000);
System.out.println("thread A is done");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}).start();
//为了让A、B线程先后执行,这里让主线程休眠10毫秒
try{
Thread.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread B is waiting to get lock");
synchronized(lock){
try {
System.out.println("thread B get lock");
System.out.println("thread B is sleeping");
Thread.sleep(10);
System.out.println("thread B is done");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}).start();
}
}
运行结果:
thread A is waiting to get lock
thread A get lock
thread B is waiting to get lock
thread A do wait method
thread B get lock
thread B is sleeping
thread B is done
thread A is done
2.接下来这个例子说明,sleep是没有改变锁的行为的。这里执行了sleep,但是没有把锁释放,所以B线程无法获取同步锁,直到A执行完后才能获取。
public class WaitSleepDemo {
public static void main(String[] args) {
final Object lock = new Object();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread A is waiting to get lock");
synchronized(lock){
try {
System.out.println("thread A get lock");
Thread.sleep(20);
System.out.println("thread A do wait method");
Thread.sleep(1000);
System.out.println("thread A is done");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}).start();
//为了让A、B线程先后执行,这里让主线程休眠10毫秒
try{
Thread.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread B is waiting to get lock");
synchronized(lock){
try {
System.out.println("thread B get lock");
System.out.println("thread B is sleeping");
lock.wait(10);
System.out.println("thread B is done");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}).start();
}
}
运行结果:
thread A is waiting to get lock
thread A get lock
thread B is waiting to get lock
thread A do wait method
thread A is done
thread B get lock
thread B is sleeping
thread B is done