一、sleep()介紹java
sleep()定義在Thread.java中。sleep()的做用是讓當前線程休眠,即當前線程會從「運行狀態」進入到「休眠(阻塞)狀態」。sleep()會指定休眠時間,線程休眠時間會大於/等於該休眠時間;在線程被從新喚醒時,它會由「阻塞狀態」變爲「就緒狀態」,從而等待CPU的調度執行小程序
二、sleep()示例this
class ThreadA extends Thread { public ThreadA(String name) { super(name); } public synchronized void run() { try { for(int i = 0;i < 10;i++) { System.out.printf("%s [%d]: %d\n",this.getName(),this.getPriority(),i); if(i%4 == 0) Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class SleepTest { public static void main(String[] args) { ThreadA t1 = new ThreadA("t1"); t1.start(); } }
運行結果:spa
t1 [5]: 0 t1 [5]: 1 t1 [5]: 2 t1 [5]: 3 t1 [5]: 4 t1 [5]: 5 t1 [5]: 6 t1 [5]: 7 t1 [5]: 8 t1 [5]: 9
結果說明:線程
一個簡單的小程序,當i%4==0的時候,線程休眠100mscode
三、sleep()與wait()的比較blog
wait()的做用是讓當前線程由「運行狀態」進入「等待狀態」的同時,也會釋放同步鎖。而sleep()的做用是讓當前線程由「運行狀態」進入「休眠狀態」。可是sleep()不會釋放同步鎖get
示例:同步
public class SleepLockTest { private static Object obj = new Object(); public static void main(String[] args) { ThreadA t1 = new ThreadA("t1"); ThreadA t2 = new ThreadA("t2"); t1.start(); t2.start(); } static class ThreadA extends Thread { public ThreadA(String name) { super(name); } public void run() { synchronized (obj) { try { for(int i = 0;i <10;i++) { System.out.printf("%s: %d\n",this.getName(),i); if(i%4 == 0) Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } } } } }
運行結果:it
t1: 0 t1: 1 t1: 2 t1: 3 t1: 4 t1: 5 t1: 6 t1: 7 t1: 8 t1: 9 t2: 0 t2: 1 t2: 2 t2: 3 t2: 4 t2: 5 t2: 6 t2: 7 t2: 8 t2: 9
結果說明:
主線程中啓動了兩個線程t1和t2。t1和t2在run()會引用同一個同步鎖,synchronized(obj)。在t1運行的過程當中,雖然調用了sleep(),可是t2沒法獲取CPU執行權,由於t1沒有釋放鎖