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

我试图理解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 : NEW

Running Mythread.

State of thread : RUNNABLE

第2行的输出是我不明白的.当正在执行线程实例的run()方法时,它如何处于RUNNABLE状态?我在书中看到了一个RUNNING状态(SCJP Suncertified Programmer).它不应该显示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,multithreading

来源: https://codeday.me/bug/20190611/1219410.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值