LockSupport是对Unsafe的一些封装。下面对一些常见方法进行解释。主要提供线程的park和unpark方法。
/**
* 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.
*/
public static void park() {
//第一个参数指明时间是绝对的还是相对的。false代表相对时间。
//第二个参数是具体需要wait的时间。如果是0则没有期限
//park方法要求线程等待许可。Unpark则释放许可。如果先调用unpark再调用park,那么park将不会暂停线程
UNSAFE.park(false, 0L);
}
//上述方法支持一个blocker参数。这个并没有什么什么实际意义。但是在线程jstack dump出来堆栈的时候,会打出来这个waiting for的对象。有助于开发人员调试问题。
public static void park(Object blocker) {
Thread t = Thread.currentThread();
setBlocker(t, blocker);
UNSAFE.park(false, 0L);
setBlocker(t, null);
}
private static void setBlocker(Thread t, Object arg) {
// Even though volatile, hotspot doesn't need a write barrier here.
UNSAFE.putObject(t, parkBlockerOffset, arg);
}
//当然,上述方法同样有自己的有时间限制的版本。
public static void parkNanos(Object blocker, long nanos) {
if (nanos > 0) {
Thread t = Thread.currentThread();
setBlocker(t, blocker);
UNSAFE.park(false, nanos);
setBlocker(t, null);
}
}
Thread线程如下
public class Thread implements Runnable {
...
/**
* The argument supplied to the current call to
* java.util.concurrent.locks.LockSupport.park.
* Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
* Accessed using java.util.concurrent.locks.LockSupport.getBlocker
*/
volatile Object parkBlocker;
...
}