程序员

park/unpark原理及使用

2023-11-30  本文已影响0人  我可能是个假开发

一、基本使用

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 相比:

二、原理

每个线程都有自己的一个 Parker 对象,由三部分组成

调用 park 看需不需要停下来:

调用 unpark:

多次调用 unpark 只会设置一次_counter 为1

场景一

image.png
  1. 当前线程调用 Unsafe.park() 方法
  2. 检查 _counter ,本情况为 0,这时,获得 _mutex 互斥锁
  3. 线程进入 _cond 条件变量阻塞
  4. 设置 _counter = 0

场景二

image.png
  1. 调用 Unsafe.unpark(Thread_0) 方法,设置 _counter 为 1
  2. 唤醒 _cond 条件变量中的 Thread_0
  3. Thread_0 恢复运行
  4. 设置 _counter 为 0

场景三

image.png
  1. 调用 Unsafe.unpark(Thread_0) 方法,设置 _counter 为 1
  2. 当前线程调用 Unsafe.park() 方法
  3. 检查 _counter ,本情况为 1,这时线程无需阻塞,继续运行
  4. 设置 _counter 为 0
上一篇 下一篇

猜你喜欢

热点阅读