線程進入休眠狀態的三種方式:Thread.sleep、Object.wait、LockSupport.park

一、線程睡眠Thread.sleep

1)需要指定睡眠時間,如

Thread.sleep(10_000);// 睡眠10秒
// TimeUnit.MINUTES.sleep(1);// 睡眠一分鐘

2)睡眠時線程狀態爲TIMED_WAITING(限期等待)。

3)需要捕獲InterruptedException異常。

4)不會釋放持有的鎖。

二、線程等待Object.wait

1)可以指定等待時間,通過notify()或者notifyAll()喚醒,推薦notifyAll()。注意,notify需要在wait之後執行。

2)等待時狀態爲WAITING(無限期等待)。

3)需要捕獲InterruptedException異常。

4)需要在synchronized同步內使用會釋放持有的鎖。

三、線程暫停LockSupport.park

1)通過信號量實現的阻塞,類似Semaphore,只不過許可不能累積,並且最多只能有一個,可以指定暫停時間,通過unpark喚醒。注意,unpark可以比park先執行。

2)暫停時狀態爲WAITING(無限期等待)。

3)無需捕獲InterruptedException異常,但是可以響應中斷。

4)不會釋放持有的鎖。

以下是一個先進先出 (first-in-first-out) 非重入鎖類的框架(摘自官方文檔)

class FIFOMutex {
   private final AtomicBoolean locked = new AtomicBoolean(false);
   private final Queue<Thread> waiters
     = new ConcurrentLinkedQueue<Thread>();

   public void lock() {
     boolean wasInterrupted = false;
     Thread current = Thread.currentThread();
     waiters.add(current);

     // Block while not first in queue or cannot acquire lock
     while (waiters.peek() != current ||
            !locked.compareAndSet(false, true)) {
       LockSupport.park(this);
       if (Thread.interrupted()) // ignore interrupts while waiting
         wasInterrupted = true;
     }

     waiters.remove();
     if (wasInterrupted)          // reassert interrupt status on exit
       current.interrupt();
   }

   public void unlock() {
     locked.set(false);
     LockSupport.unpark(waiters.peek());
   }
 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章