概述
我试图理解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
最后
以上就是美丽衬衫为你收集整理的java线程的run()方法_在run()方法中的线程状态(Java)的全部内容,希望文章能够帮你解决java线程的run()方法_在run()方法中的线程状态(Java)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复