在学习CountDownLatch的时候非常关心它是如何阻塞线程和唤醒线程的。最后就追踪到了LockSupport。这个类有着wait(),notify()类似的功能,不过更精准。
LockSupport.park(Thread thread),//阻塞thread
LockSupport.unpark(Thread thread) //唤醒thread
(PS,这个类中还有其他的方法,不过基本是成对出现的)
这两个方法是相对应的,其实这两个方法调用的是Unsafe中对应的方法,而Unsafe是没有开源的。不过可以估计里面是通过JNI实现的。这里就不在细纠。因为我在看notify和wait方法的时候也是调用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();
}
}
}