sleep與wait區別:
1.sleep方法是線程靜態方法,wait方法是Object對象方法;
2.sleep使線程休眠,不會釋放鎖;wait方法是在獲取鎖情況下進行等待的,等待時會釋放鎖;
3.都可以響應中斷。
public class Test { static Object lock = new Object(); public static void main(String[] args) { //休眠測試 Thread t = new Thread(() -> { System.out.println("休眠"); long s = System.currentTimeMillis(); try { Thread.sleep(100000); } catch (InterruptedException e) { System.out.println("結束休眠2 " + (System.currentTimeMillis() - s)); } }); t.start(); System.out.println("中斷休眠"); t.interrupt(); try { Thread.sleep(5000); } catch (InterruptedException e) { } //wait測試 System.out.println("-----------wait---------"); Thread t1 = new Thread(() -> { synchronized(lock) { System.out.println("等待"); long s = System.currentTimeMillis(); try { lock.wait(); } catch (InterruptedException e) { System.out.println("結束wait1 " + (System.currentTimeMillis() - s)); } } }); t1.start(); System.out.println("中斷wait"); t1.interrupt(); } }
輸出:
中斷休眠 休眠 結束休眠2 0 -----------wait--------- 中斷wait 等待 結束wait1 0