LockSupport.unpark(thread1);

会给当前指定的线程,发放一个许可,底层是给一个 count + 1 的操作,默认 count 为 0

LockSupport.park();

当前线程遇到 park 方法首先会检查 count 是否为 0,如果 count 为 0,则进行阻塞操作,等待许可,一旦发现许可,便可以解阻塞

java.util.concurrent.locks.Condition 类下的 await()signal() 的实现就是用 LockSupport 来实现的

  1. public final void await() throws InterruptedException {
  2. if (Thread.interrupted())
  3. throw new InterruptedException();
  4. Node node = addConditionWaiter();
  5. int savedState = fullyRelease(node);
  6. int interruptMode = 0;
  7. while (!isOnSyncQueue(node)) {
  8. LockSupport.park(this);
  9. if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
  10. break;
  11. }
  12. if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
  13. interruptMode = REINTERRUPT;
  14. if (node.nextWaiter != null) // clean up if cancelled
  15. unlinkCancelledWaiters();
  16. if (interruptMode != 0)
  17. reportInterruptAfterWait(interruptMode);
  18. }
  1. final boolean transferForSignal(Node node) {
  2. /*
  3. * If cannot change waitStatus, the node has been cancelled.
  4. */
  5. if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
  6. return false;
  7. /*
  8. * Splice onto queue and try to set waitStatus of predecessor to
  9. * indicate that thread is (probably) waiting. If cancelled or
  10. * attempt to set waitStatus fails, wake up to resync (in which
  11. * case the waitStatus can be transiently and harmlessly wrong).
  12. */
  13. Node p = enq(node);
  14. int ws = p.waitStatus;
  15. if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
  16. LockSupport.unpark(node.thread);
  17. return true;
  18. }