/**
* Unblock the given thread blocked on <tt>park</tt>, or, if it is
* not blocked, cause the subsequent call to <tt>park</tt> not to
* block. Note: this operation is "unsafe" solely because the
* caller must somehow ensure that the thread has not been
* destroyed. Nothing special is usually required to ensure this
* when called from Java (in which there will ordinarily be a live
* reference to the thread) but this is not nearly-automatically
* so when calling from native code.
* @param thread the thread to unpark.
*
*/
public native void unpark(Object thread);
park方法用於Block current thread。在以下情況下返回
1 針對當前線程已經調用過unpark(多次調用unpark的效果和調用一次unpark的效果一樣)
public static void main(String[] args) throws Exception { Unsafe unsafe = UnsafeUtil.getUnsafe(); Thread currThread = Thread.currentThread(); unsafe.unpark(currThread); unsafe.unpark(currThread); unsafe.unpark(currThread); unsafe.park(false, 0); System.out.println("SUCCESS!!!"); }
park方法馬上返回
2 在當前線程中斷的時候或者調用unpark的時候
public static void main(String[] args) throws Exception { Unsafe unsafe = UnsafeUtil.getUnsafe(); Thread currThread = Thread.currentThread(); new Thread(()->{ try { Thread.sleep(3000); currThread.interrupt(); //unsafe.unpark(currThread); } catch (Exception e) {} }).start(); unsafe.park(false, 0); System.out.println("SUCCESS!!!"); }
park在3秒后返回
3 如果是相對時間也就是isAbsolute為false(注意這里后面的單位納秒)到期的時候
public static void main(String[] args) throws Exception { Unsafe unsafe = UnsafeUtil.getUnsafe(); //相對時間后面的參數單位是納秒 unsafe.park(false, 3000000000l); System.out.println("SUCCESS!!!"); }
3秒后 park返回
4 如果是絕對時間也就是isAbsolute為true(注意后面的單位是毫秒)到期的時候
public static void main(String[] args) throws Exception { Unsafe unsafe = UnsafeUtil.getUnsafe(); long time = System.currentTimeMillis()+3000; //絕對時間后面的參數單位是毫秒 unsafe.park(true, time); System.out.println("SUCCESS!!!"); }
3秒后 park返回
5 無理由的返回
unpark方法最好不要在調用park前對當前線程調用unpark
/** * Unblock the given thread blocked on <tt>park</tt>, or, if it is * not blocked, cause the subsequent call to <tt>park</tt> not to * block. Note: this operation is "unsafe" solely because the * caller must somehow ensure that the thread has not been * destroyed. Nothing special is usually required to ensure this * when called from Java (in which there will ordinarily be a live * reference to the thread) but this is not nearly-automatically * so when calling from native code. * @param thread the thread to unpark. * */ public native void unpark(Object thread);