gpt4 book ai didi

java - run() 方法中的线程状态 (Java)

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

我想了解 Java 中的多线程。在我介绍 Java 线程可能处于的各种状态时(新的、可运行的、正在运行的、等待/阻塞的、死的)。我尝试运行一些简单的代码来检查线程的状态。

我创建了一个 MyThread 类,它扩展了 Thread 并覆盖了 run() 方法。

package com.practice.threads;

public class MyThread extends Thread {

@Override
public void run() {
super.run();
System.out.println("Running Mythread.");
System.out.println("State of thread : " + this.getState()); // line 2
}

}

现在我已经创建了一个简单的类来测试线程的状态:

package com.practice.threads;

public class ThreadStateDemo {

/**
* @param args
*/
public static void main(String[] args) {
MyThread myThread = new MyThread();
System.out.println("State of thread : " + myThread.getState()); // line 1
myThread.start();

}

}

运行这个类给出以下输出:

State of thread : NEWRunning Mythread.State of thread : RUNNABLE

第 2 行的输出是我不明白的东西。一个线程实例的run()方法在执行时,怎么会是RUNNABLE状态呢?我在一本书(SCJP Suncertified Programmer)中看到了 RUNNING 状态的提及。它不应该显示 RUNNING 吗?

最佳答案

这本书有一个(容易犯的)错误,状态是RUNNABLE,而不是RUNNING。没有 RUNNING 状态,请参阅 the JavaDoc :

NEW
A thread that has not yet started is in this state.
RUNNABLE
A thread executing in the Java virtual machine is in this state.
BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED
A thread that has exited is in this state.

(我的重点)

这只是一个奇怪的、有点迂腐的名字,因为从技术上讲,它只有在操作系统运行时才会运行。但从 JVM 的角度来看,它正在“运行”。

关于java - run() 方法中的线程状态 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38071944/

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