方法區別
- sleep方法
sleep讓出cpu資源,但是不會釋放鎖,不干涉鎖行爲;
哪裏都可以使用 - wait方法
wait是既讓出cpu資源,又會釋放鎖資源;
一般使用在同步方法或者同步代碼塊中
案例分析
public class WaitSleepDemo {
public static void main(String[] args) throws InterruptedException {
final Object lock = new Object();
new Thread(() -> {
System.out.println("Thread A is waiting for the lock");
synchronized (lock) {
System.out.println("Thread A get lock");
try {
Thread.sleep(20);
System.out.println("Thread A do wait method");
lock.wait(1000);
System.out.println("Thread A done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Thread.sleep(10);
new Thread(() -> {
System.out.println("Thread B is waiting for the lock");
synchronized (lock) {
System.out.println("Thread B get lock");
try {
System.out.println("Thread B is sleeping 10 ms");
Thread.sleep(10);
System.out.println("Thread B done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
執行結果:
public class WaitSleepDemo2 {
public static void main(String[] args) throws InterruptedException {
final Object lock = new Object();
new Thread(() -> {
System.out.println("Thread A is waiting for the lock");
synchronized (lock) {
System.out.println("Thread A get lock");
try {
Thread.sleep(20);
System.out.println("Thread A do wait method");
Thread.sleep(1000);
System.out.println("Thread A done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Thread.sleep(10);
new Thread(() -> {
System.out.println("Thread B is waiting for the lock");
synchronized (lock) {
System.out.println("Thread B get lock");
try {
System.out.println("Thread B is sleeping 10 ms");
lock.wait(10);
System.out.println("Thread B done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
總結
從上面兩個案例打印可以看得出,第一個案例的A線程執行wait方法時,獲取到鎖的;但是第二個案例A線程執行的wait方法處換成sleep之後,B線程無法在A線程結束前獲取到鎖!由此得出文章開始的結論。