gpt4 book ai didi

java - 为什么线程处于可运行状态时对象没有锁定?

转载 作者:搜寻专家 更新时间:2023-11-01 01:25:19 25 4
gpt4 key购买 nike

我有 Run 类(class)。很简单,就是打印, hibernate 然后打印;

    public class Run implements Runnable {

@Override
public void run() {
System.out.println("START RUN");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("FINISH RUN");
}
}

好的,现在我正在写测试;

public static synchronized void main(String[] args) throws InterruptedException {

Run r = new Run();
Thread t = new Thread(r, "TEST");
t.start();

// EXECYTE THE CODE WHULE THREAD "TEST" IS RUNNABLE
synchronized (t) {
System.out.println(t.getState());
t.wait();
}
System.out.println("Y");

// SLEEP THREAD "TEST" TO BE EXECUTED DURING THE TIME
Thread.sleep(100);
synchronized (t) {
System.out.println(t.getState());
t.wait();
}
System.out.println("Y2");
}

问题 1: 当线程“TEST”正在执行时,我尝试 wait()。此时线程状态为“RUNNABLE”。由于这种状态,它等待,我不明白为什么?如果状态将是“已终止”或"new",则 wait() 有效;如果我删除 t.start(),线程状态将为"new",因此等待也有效。你能告诉我发生了什么吗?

输出:

START RUN
RUNNABLE
FINISH RUN
Y
TERMINATED`

最佳答案

这方面的文档很少。 Thread#join(long) 的 javadoc州

As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

它明确表示不要做你目前正在做的事情。即,在 Thread 对象上同步,并在同一对象上调用 wait

synchronized (t) {
System.out.println(t.getState());
t.wait();
}

在您的代码的当前执行中。当您的 TEST 线程正在 hibernate 时,您的主线程到达上面的 t.wait() 调用。 TEST 然后唤醒并终止。当它终止时,它调用 notifyAllt.wait() 唤醒您的主线程。

当您的主线程随后到达第二个 t.wait() 时,您的程序中没有任何东西可以唤醒它,因此您的程序只是挂起。


总而言之:不要将 Thread 对象监视器用于任何事情

关于java - 为什么线程处于可运行状态时对象没有锁定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36520890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com