LockSupport的JDK的文档描述:Basic thread blocking primitives for creating locks and other synchronization classes.(对于创建lock和其他同步类的基础线程原语)。在JUC中有大量使用!
1 示例:
在主线程中调用LockSupport.park(currentThread);将组线程阻塞,然后通过子线程完成5秒睡眠换后唤醒主线程。
import java.util.concurrent.locks.LockSupport; public class LockSupportDemo { public static void main(String[] args) { //获取当前线程 final Thread currentThread = Thread.currentThread(); Runnable runnable = new Runnable() { @Override public void run() { try { //睡眠5秒,等待主线程调用park Thread.sleep(5000); System.out.println("子线程进行unpark操作!"); // 进行唤醒给定的currentThread线程 LockSupport.unpark(currentThread); } catch (InterruptedException e) { e.printStackTrace(); } } }; new Thread(runnable).start(); System.out.println("开始阻塞!"); // 进行阻塞给定的currentThread线程 LockSupport.park(currentThread); System.out.println("结束阻塞!"); } }
示例2:
import java.util.concurrent.locks.LockSupport; public class LockSupportDemo { public static void main(String[] args) { //获取当前线程 final Thread currentThread = Thread.currentThread(); //在park之前先进行一次unpark LockSupport.unpark(currentThread); System.out.println("开始阻塞!"); // 由于在park之前进行了一次unpark,所以会低调本次的park操作。因而不会阻塞在此处 LockSupport.park(currentThread); System.out.println("结束阻塞!"); } }