LockSupport源码分析

       在学习CountDownLatch的时候非常关心它是如何阻塞线程和唤醒线程的。最后就追踪到了LockSupport。这个类有着wait()notify()类似的功能,不过更精准。

       LockSupport.park(Thread thread)//阻塞thread

       LockSupport.unpark(Thread thread) //唤醒thread

       PS,这个类中还有其他的方法,不过基本是成对出现的)

       这两个方法是相对应的,其实这两个方法调用的是Unsafe中对应的方法,而Unsafe是没有开源的。不过可以估计里面是通过JNI实现的。这里就不在细纠。因为我在看notifywait方法的时候也是调用JNI

 

下面是一个测试用例,里面实现了一个线程阻塞,而开启子线程唤醒阻塞线程。

public class LockSupportTest extends Thread {
	
	//static LockSupportSon thread1;

	static LockSupportTest thread2;
	
	private Thread currentThread;
	
	public LockSupportTest(){}
	
	public LockSupportTest(Thread currentThread){
		this.currentThread = currentThread;
	}

	public static void main(String[] args) {
		//thread1 = new LockSupportSon();
		//thread1.start();
		thread2 = new LockSupportTest(Thread.currentThread());
		thread2.start();
		testPark();
	}

	public static void testPark() {
		System.out.println("["+new Date()+"]before>>>>>>");
		LockSupport.park(Thread.currentThread());
		System.out.println("["+new Date()+"]after>>>>>>>");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		try {
			System.out.println("thread2 before>>>>");
			Thread.sleep(5000L);
			LockSupport.unpark(currentThread);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}
}


 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值