LockSupport
J.U.C框架中有一个叫做LockSupport的类,可以精准地阻塞和唤醒特定的线程,并作为其他同步类的原语。
LockSupport包含一个park(Object blocker)和unpark(Object blocker)方法,分别用于阻塞和唤醒。
举个例子,下面的代码包含一个线程thread1和主线程,在thread1中调用park方法,在主线程中调用unpark,然后打印thread1的状态:
import java.util.concurrent.locks.LockSupport;
public class Main{
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread 1 start");
LockSupport.park(Thread.currentThread());
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread 1 end");
}
});
thread1.start();
System.out.println("main thread start,thread1 "+thread1.getState());
Thread.sleep(2000);
System.out.println("main thread running,thread1 "+thread1.getState());
LockSupport.unpark(thread1);
Thread.sleep(6000);
System.out.println("main thread end,thread1 "+thread1.getState());
}
}
执行结果:
thread 1 start
main thread start,thread1 RUNNABLE
main thread running,thread1 WAITING
thread 1 end
main thread end,thread1 TERMINATED
可以看到,park之后thread1变成WAITTING,unpark之后唤醒继续执行直到结束