有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java锁支持。upark()可以在锁定支持之前发生。park()方法,但在下面的代码中,为什么它会阻止代码

锁支架。upark()可以在锁定支持之前发生。park()方法,但在下面的代码中,它为什么会阻止代码。在我的代码中,在主线程中有4个锁支持。unpark(t1),实际上,当我运行线程t1时,它只能获得一次访问,LockSupport。park()可以使用一个并返回,但它会阻止代码,为什么

public class LockSupportDemo{
public static Object u = new Object();
static ChangeObjectThread t1 = new ChangeObjectThread("t1");
public static class ChangeObjectThread extends Thread{

    public ChangeObjectThread(String name)
    {
        super.setName(name);
    }

    @Override
    public void run() {
        synchronized (u)
        {

            LockSupport.park(Thread.currentThread());
            System.out.println("in "+ getName());
            if(Thread.interrupted())
            {
                System.out.println(getName()+" interrupted");
            }
        }
        System.out.println(getName() +"isOver");

    }
}

public static void main(String[] args) throws InterruptedException {
    LockSupport.unpark(t1);
    LockSupport.unpark(t1);
    LockSupport.unpark(t1);
    LockSupport.unpark(t1);
    LockSupport.unpark(t1);
    t1.start();
 }
 }

共 (1) 个答案

  1. # 1 楼答案

    关于LockSupport.unpark的Javadoc非常明确:

    Makes available the permit for the given thread, if it was not already available. If the thread was blocked on park then it will unblock. Otherwise, its next call to park is guaranteed not to block. This operation is not guaranteed to have any effect at all if the given thread has not been started.

    你上面所做的是行不通的

    为了达到同样的效果,您可以启动线程,但让它等待,直到您使用wait/notify信号在主线程中调用unpark。或者,如果你需要一些快速而肮脏的东西(因为这似乎更多的是探索LockSupport,而不是编写生产代码),那么你甚至可以在run方法的开头使用Thread.sleep(1000);