一、基本使用
LockSupport 类中的方法
// 暂停当前线程
LockSupport.park();
// 恢复某个线程的运行
LockSupport.unpark(暂停线程对象)
1.先 park 再 unpark
@Slf4j
public class ParkTest {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("park");
LockSupport.park();
log.debug("resume");
},"t1");
t1.start();
Thread.sleep(2000);
log.debug("unpark");
LockSupport.unpark(t1);
}
}
12:29:10.364 [t1] DEBUG juc.parkunpark.ParkTest - park
12:29:11.366 [main] DEBUG juc.parkunpark.ParkTest - unpark
12:29:11.366 [t1] DEBUG juc.parkunpark.ParkTest - resume
2.先 unpark 再 park
public class ParkTest {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("park");
LockSupport.park();
log.debug("resume");
},"t1");
t1.start();
Thread.sleep(1000);
log.debug("unpark");
LockSupport.unpark(t1);
}
}
12:30:28.718 [main] DEBUG juc.parkunpark.ParkTest - unpark
12:30:29.715 [t1] DEBUG juc.parkunpark.ParkTest - park
12:30:29.715 [t1] DEBUG juc.parkunpark.ParkTest - resume
与 Object 的 wait & notify 相比:
- wait,notify 和 notifyAll 必须配合 Object Monitor 一起使用,而 park,unpark 不需要
- park & unpark 是以线程为单位来【阻塞】和【唤醒】线程,而 notify 只能随机唤醒一个等待线程,notifyAll是唤醒所有等待线程,就不那么【精确】
- park & unpark 可以先 unpark,而 wait & notify 不能先 notify
二、原理
每个线程都有自己的一个 Parker 对象,由三部分组成
- _counter :0/1 (1:阻塞 0:不阻塞)
- _cond :条件变量
- _mutex
调用 park 看需不需要停下来:
- 如果_counter 为0,则进入条件变量_cond 中等待,设置_counter为0。
- 如果_counter 为1,不需停留,继续执行,设置_counter为0。
调用 unpark:
- 设置counter为1,如果这时线程在条件变量_cond 中等待,就唤醒让他继续执行,设置_counter为0。
- 设置counter为1,如果这时线程还在运行,则继续执行,_counter置为0。
多次调用 unpark 只会设置一次_counter 为1
场景一
![](https://img.haomeiwen.com/i4807654/fa007dd2d8009119.png)
- 当前线程调用 Unsafe.park() 方法
- 检查 _counter ,本情况为 0,这时,获得 _mutex 互斥锁
- 线程进入 _cond 条件变量阻塞
- 设置 _counter = 0
场景二
![](https://img.haomeiwen.com/i4807654/639732a535d7e4b6.png)
- 调用 Unsafe.unpark(Thread_0) 方法,设置 _counter 为 1
- 唤醒 _cond 条件变量中的 Thread_0
- Thread_0 恢复运行
- 设置 _counter 为 0
场景三
![](https://img.haomeiwen.com/i4807654/37d19aac091c76aa.png)
- 调用 Unsafe.unpark(Thread_0) 方法,设置 _counter 为 1
- 当前线程调用 Unsafe.park() 方法
- 检查 _counter ,本情况为 1,这时线程无需阻塞,继续运行
- 设置 _counter 为 0
网友评论