有 Java 编程相关的问题?

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

java线程。start()方法锁定了哪个对象?

我有一个疑问,如果Thread.start()方法是synchronized,那么它一定需要对某个对象的监视器进行锁定

如何检查此项并获取对该对象的引用

public class ThreadDemo extends Thread {
    public static void main(String[] args) {
        new ThreadDemo().start();
        for (int i = 0; i < 3; i++) {
            System.out.println("Parent thread :" + currentThread());
        }
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println(currentThread() + " Child thread holding lock : " + currentThread().holdsLock(this));
        }
    }
}

我的输出:

Parent thread : Thread[main,5,main]
Thread[Thread-0,5,main] Child thread holding lock : false
Parent thread : Thread[main,5,main]
Thread[Thread-0,5,main] Child thread holding lock : false
Parent thread : Thread[main,5,main]
Thread[Thread-0,5,main] Child thread holding lock : false

预期:

因为我正在检查当前对象上的锁,该对象应该返回true,而不是false

如果我遗漏了什么,请纠正我

在建议的帖子中,它显示了我们可以通过方法线程检查线程是否持有某个对象的锁。holdsLock(对象),在检查之前,我们有对象的参考。但我想确认start()方法是否对某个对象持有锁。如果是,那么是哪一个


共 (1) 个答案

  1. # 1 楼答案

    你的期望是不合理的。我希望锁的目的是让新创建的线程能够看到调用start的线程提供的所有信息,比如调用什么对象的函数。当您到达run时,新创建的线程必须访问该信息,因此创建线程应该在该点之前释放锁