关于 Java 中的 LockSupport.getBlocker(线程 t) 的问题

A Question about LockSupport.getBlocker(Thread t) in Java

LockSupport.getBlocker(Thread t)

Returns the blocker object supplied to the most recent invocation of a park method that has not yet unblocked, or null if not blocked.

为什么这段代码中的打印输出会输出不同的对象?我是不是误会了LockSupport.getBlocker(Thread t)


public static void main(String[] args) throws InterruptedException {
    Object lock = new Object();
    Thread t1 = new Thread(() -> {
        System.out.println("sub thread lock = " + lock);
        LockSupport.park(new Object());
    });
    t1.start();
    Thread.sleep(5000);
    Object getBlocker = LockSupport.getBlocker(t1);
    System.out.println("main thread blocker = " + getBlocker);
    System.out.println("is blocker same ? " + getBlocker == lock);
    LockSupport.unpark(t1);
    t1.join();
}

输出:

sub thread lock = java.lang.Object@6edf6345
main thread blocker = java.lang.Object@77459877
false
LockSupport.park(new Object());

您正在使用全新的物品停车。与 lock.

一起停车
LockSupport.park(lock);

您对LockSupport.getBlocker(Thread t)方法的理解是正确的。但是,您的用法可能是错误的,因为您在 park 方法中传递了一个不同于 lock 的对象。

为了检查 return 为真,将 lock 对象传递给 park 方法。

LockSupport.park(lock);

为此,您可能需要将 lock 对象设为 final