gpt4 book ai didi

java - Java 多线程中线程状态如何工作?

转载 作者:行者123 更新时间:2023-12-01 09:57:27 25 4
gpt4 key购买 nike

public class ThreadState{
public static void main(String[] args){
Thread one = new Thread(new Runnable(){
@Override
public void run(){
System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().getState());
}
});
Thread two = new Thread(new Runnable(){
@Override
public void run(){
System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().getState());
}
});
System.out.println(one.getState());
System.out.println(two.getState());

one.start();
two.start();

System.out.println(one.getState());
System.out.println(two.getState());
System.out.println(one.getState());
System.out.println(two.getState());

System.out.println("Main ");
}
}

我正在尝试学习java中的Thread.State,但我对它们之间感到困惑。当我运行上面的代码时,我得到了多个结果(我知道是因为多线程)。

但我无法理解它们的状态。

1)这是我想学习的两个输出,你能解释一下其中的任何一个吗?

NEW
NEW
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
Thread-0 RUNNABLE
Thread-1 RUNNABLE
Main

第二个是这个。

NEW 
NEW
RUNNABLE
BLOCKED
BLOCKED // 2) Why go to again BLOCKED state? as before it was in RUNNABLE state
BLOCKED
Main
Thread-0 RUNNABLE
Thread-1 RUNNABLE

我已经知道什么是 NEW 状态,什么是 RUNNABLE 状态。但我对 BLOCKED 和 WAITING 状态感到困惑。

Student object1 = new Student(); // any shared resource

Thread t1 = new Thread(/*......*/); => NEW State
Thread t2 = new Thread(/*......*/); => NEW State

t1.start(); => RUNNABLE STATE
t2.start(); => RUNNABLE STATE

`t1` and `t2` trying to get lock on object1 and `t1` successfully got locked on object1.

3) 现在t2将处于BLOCKED状态或WAITING状态?

`t1` called `wait()` method and released lock.
`t2` got the lock and `t1` now in WAITING state.

`t2` called `notify();` and released lock.
`t1` got the lock

4) t2 将处于 BLOCKED 状态还是等待状态?

`t1.run();` finished => TERMINATED State
`t2.run();` finished => TERMINATED State

5) 即使线程死亡后,JVM 仍保留每个线程的历史记录吗?如果不是,那么 JVM 如何显示已经消失的线程的终止状态?

最佳答案

BLOCKED 表示:“等待监视器锁而被阻塞的线程处于此状态。”这意味着涉及同步。您没有使用任何同步块(synchronized block),但线程在内部使用。鉴于它是 RUNNING 然后是 BLOCKED,它可能是在私有(private) Thread.exit() 方法中发生的同步。例如,Group.threadTermminate() 在组上同步。

WAITING 表示线程已调用 Object.wait()。为了做到这一点,它必须拥有监视器(与调用的对象等待相关联),因此它不能在该监视器上被阻止。

对于 3 和 4,如果我遵循,答案是 3) BLOCKED 和 4) RUNNING 或 TERMINATED

至于 JVM 是否保留历史记录,我不确定这是 JVM 的要求,但只要您有对 Thread 对象的引用,您应该能够看到最后的状态是什么。请记住,Thread 对象只是线程对象的表示。实际线程是特定于操作系统/硬件的。

关于java - Java 多线程中线程状态如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37077081/

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