线程进入休眠状态的三种方式: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());
   }
 }

 

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