其他分享
首页 > 其他分享> > park和unpark

park和unpark

作者:互联网

park和unpark

文章目录

1.基本使用

它们是 LockSupport 类中的方法

// 暂停当前线程
LockSupport.park();
// 恢复某个线程的运行
LockSupport.unpark(暂停线程对象)

先 park 再 unpark

2.演示代码

/**
 * 暂停当前线程
 * LockSupport.park();
 * 恢复某个线程的运行
 * LockSupport.unpark(暂停线程对象)
 */
@Test
public void testPark_Unpark() {
    //线程1
    Thread t1 = new Thread(() -> {
        log.debug("start...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.debug("park...");
        //park
        LockSupport.park();
        log.debug("resume...");
    }, "t1");
    t1.start();

    //主线程中unpark
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    log.debug("umpark...");
    LockSupport.unpark(t1);

    //等待t1执行完毕
    try {
        t1.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

在这里插入图片描述
unpark可以在park之前,之后调用。在park之前调用,可以恢复线程运行。

在这里插入图片描述
在这里插入图片描述

3.特点

与 Object 的 wait & notify 相比:

4.park()/unpark()底层原理(重要)

在这里插入图片描述
每个线程都有自己的一个 Parker 对象,由三部分组成 _counter , _cond 和 _mutex 。
打个比喻:

情况1:先park()

在这里插入图片描述

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

情况2:后调用unpark()

在这里插入图片描述

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

情况3:先调用unpark(),再调用park()

在这里插入图片描述

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

5.源码分析

public static void park(Object blocker) {
    Thread t = Thread.currentThread();  //获取当前线程
    setBlocker(t, blocker);  
    UNSAFE.park(false, 0L);  //Unsafe对象调用本地park方法(C实现的)
    setBlocker(t, null);
}
private static void setBlocker(Thread t, Object arg) {
    // Even though volatile, hotspot doesn't need a write barrier here.
    UNSAFE.putObject(t, parkBlockerOffset, arg);  //本地方法
}
public static void unpark(Thread thread) {
    if (thread != null)
        UNSAFE.unpark(thread);    //调用本地unpark方法
}
public native void unpark(Object var1);

标签:调用,Thread,counter,park,unpark,线程
来源: https://blog.csdn.net/qq_36109528/article/details/120845450