LockSupport 是提供比较底层的挂起阻塞线程的操作原语。
有点类似于suspend()。主要的接口有
LockSupport .park() 顾名思义park停车,就是把一个现场挂起。
LockSupport .unpark(t1) 开车启动o.o
与suspend的区别就是,suspend是不建议使用的有可能废除的。
且如果一个线程没有被suspend,调用resume,则会阻塞线程。
而线程没有park时调用UNpark则不会。
原因是park
/**
* Disables the current thread for thread scheduling purposes unless the
* permit is available.
* <p>If the permit is available then it is consumed and the call returns
* immediately; otherwise
* the current thread becomes disabled for thread scheduling
* purposes and lies dormant until one of three things happens:
*
* <ul>
* <li>Some other thread invokes {@link #unpark unpark} with the
* current thread as the target; or
*
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* the current thread; or
*
* <li>The call spuriously (that is, for no reason) returns.
* </ul>
*
* <p>This method does <em>not</em> report which of these caused the
* method to return. Callers should re-check the conditions which caused
* the thread to park in the first place. Callers may also determine,
* for example, the interrupt status of the thread upon return.
*
挂起一个线程,除非这个许可可用。如果一个线程正在执行,则这个许可是不可用的,park就能挂起线程。
挂起到什么时候呢,就是三个情况发生。1:调用UNpark:2:别的线程interrupt这个线程。所以他是可中断的。
3:调用虚假的返回(就是这样,没有为什么),看见这个括号的就可以忽视了。
再看看UNpark
* Makes available the permit for the given thread, if it
* was not already available. If the thread was blocked on
* {@code park} then it will unblock. Otherwise, its next call
* to {@code park} is guaranteed not to block. This operation
* is not guaranteed to have any effect at all if the given
* thread has not been started.
是的一个给与的线程许可可用。如果线程被park锁住,则会解锁。否则,他将保证下次park不会锁。因为它将许可置为可用了。