執行緒休眠——Thread.sleep()
阿新 • • 發佈:2018-12-21
1、sleep介紹
sleep() 定義在Thread.java中,sleep() 的作用是讓當前執行緒休眠,即當前執行緒會從“執行狀態”進入到“休眠(阻塞)狀態”。sleep()會指定休眠時間,執行緒休眠的時間會大於/等於該指定休眠時間;線上程重新被喚醒時,它會由“阻塞狀態”變成“就緒狀態”,從而等待cpu的排程執行
2、示例:
public class YieldThread extends Thread { public YieldThread(String name) { super(name); } @Override 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(3000); } } catch (InterruptedException e) { e.printStackTrace(); } } } //測試 public class MainTest { public static void main(String args[]) { YieldThread t1 = new YieldThread("t1"); YieldThread t2 = new YieldThread("t2"); t1.start(); t2.start(); } } //結果 t1 [5]:0 t2 [5]:0 t1 [5]:1//3秒鐘後 t1 [5]:2 t1 [5]:3 t1 [5]:4 t2 [5]:1 t2 [5]:2 t2 [5]:3 t2 [5]:4 t1 [5]:5//再3秒後 t1 [5]:6 t1 [5]:7 t1 [5]:8 t2 [5]:5 t2 [5]:6 t2 [5]:7 t2 [5]:8 t1 [5]:9//再3秒後 t2 [5]:9
3、sleep()和wait()比較
wait()的作用是讓當前執行緒由“執行狀態”進入“等待(阻塞)狀態”,同時會釋放物件的同步鎖;而sleep()的作用是讓當前執行緒由“執行狀態”進入到“休眠(阻塞)狀態”,但不會釋放鎖。示例:
public class MainTest { private static Object obj = new Object(); public static void main(String args[]) { ThreadInner t1 = new ThreadInner("t1"); ThreadInner t2 = new ThreadInner("t2"); t1.start(); t2.start(); } // 靜態內部類 static class ThreadInner extends Thread { public ThreadInner(String name) { super(name); } public void run() { synchronized (obj) { for (int i = 0; i < 10; i++) { System.out.printf("%s: %d\n", this.getName(), i); if (i % 4 == 0) try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } //結果 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//兩秒後
可以看到先執行的執行緒在休眠後並沒有釋放鎖,後執行的現在只能在先執行的執行緒執行完同步程式碼塊釋放鎖之後再獲取鎖得以執行