java.util.concurrent.locks 包 中LockSupport.java 中线程挂起也采用Unsafe.park() 将线程挂起
public static void park(Object blocker) {
Thread t = Thread.currentThread();
setBlocker(t, blocker);
UNSAFE.park(false, 0L);
setBlocker(t, null);
}
Unsafe 中 park、unpatk 使用示例
// 获取 Unsafe 实例
public static Unsafe getUnsafe()
throws IllegalAccessException, NoSuchFieldException {
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
//Field unsafeField = Unsafe.class.getDeclaredFields()[0]; //也可以这样,作用相同
unsafeField.setAccessible(true);
Unsafe unsafe =(Unsafe) unsafeField.get(null);
return unsafe;
}
public static void main(String[] args)
throws NoSuchFieldException, IllegalAccessException {
Thread mainThread = Thread.currentThread();// 获取main线程
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(5);
System.out.println("subThread try to unpark mainThread");
try {
getUnsafe().unpark(mainThread); // ②休眠5s 后唤醒main 线程
} catch (Exception e) {
e.printStackTrace();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
System.out.println("park main mainThread");
getUnsafe().park(false, 0L); // ①主线程 挂起
System.out.println("unpark mainThread success");
}
输出结果:
park main mainThread
subThread try to unpark mainThread
unpark mainThread success
Process finished with exit code 0