它们是LockSupport类中的方法
//暂停当线程
LockSupport.park();
//恢复某个线程的运行
LockSupport.unpark(暂停线程对象)
public class ParkAndUnpark {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
System.out.println("t1 start");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("park");
System.out.println("暂停执行");
LockSupport.park();
System.out.println("恢复执行");
});
t1.start();
Thread.sleep(2 * 1000);
System.out.println("unpark");
LockSupport.unpark(t1);
}
}
当主线程先unpark时,子线程park时会自动unpark
public class ParkAndUnpark {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
System.out.println("t1 start");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("park");
System.out.println("暂停执行");
LockSupport.park();
System.out.println("恢复执行");
});
t1.start();
Thread.sleep(1 * 1000);
System.out.println("unpark");
LockSupport.unpark(t1);
}
}
特点
和Object的wait & notify相比:
wait,notify和notifyAll 必须配合Object Monitor一起使用,而park,unpark不必
park & unpark是以线程为单位来【阻塞】和【唤醒】线程,而notify只能水机唤醒一个等待线程,
notifyAll是唤醒所有等待线程,就不那么【精准】
park & unpark可以先unpark,而wait & notify不能先notify