java - 运行开始前的线程状态不是New,是runnable,是不是错了
问题描述
从基础学习开始,我是 Java 线程的新手,我知道创建线程时,它处于新状态。当线程处于此状态时,线程尚未开始运行
public class MainClassForThread {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new ExtendingThreadClass();
Thread t2 = new ExtendingThreadClass();
Thread t3 = new ExtendingThreadClass();
System.out.println("Before start of thread the state of thread is " + t1.currentThread().getState());
t1.start();
t2.start();
t3.start();
}
}
package Threads;
public class ExtendingThreadClass extends Thread {
public void run() {
System.out.println("Thread running : " + Thread.currentThread().getId());
for (int i = 0; i < 100; i++) {
System.out.println("Thread " + Thread.currentThread().getName() + " is running for value of i " + i);
System.out.println("State " + Thread.currentThread().getState());
}
}
}
我期望第一行代码的输出应该是新的,因为线程 t1 尚未启动,但输出如下
Before start of thread the state of thread is RUNNABLE
Thread running : 10
Thread running : 12
Thread Thread-2 is running for value of i 0
Thread running : 11
Thread Thread-0 is running for value of i 0
State RUNNABLE
Thread Thread-0 is running for value of i 1
State RUNNABLE
Thread Thread-0 is running for value of i 2
解决方案
问题是这一行:
System.out.println("Before start of thread the state of thread is " + t1.currentThread().getState());
你得到当前线程,并且当前线程正在运行。
您可能不想获取当前线程的状态,因此将该行更改为
System.out.println("Before start of thread the state of thread is " + t1.getState());
推荐阅读
- git - 在 git 合并期间忽略文件。即文件存在于分支A但不存在于分支B。合并A-> B时保持这种方式
- apache-beam - GroupByKey 不更新很长的 PTransform 与窗口
- java - 用于定位 ifram 的循环并切换到它不起作用
- java - “在项目同步成功之前预览不可用”
- python - How to create several smaller lists that contain specified indices based on a larger list in a nested list?
- spring-boot - 将 Grails 3 prod war 部署到 Tomcat9 的 MapperListener 错误是什么?
- ruby-on-rails - 对嵌套在具有命名空间问题的模块中的类的请求规范失败
- three.js - 三个透明的js后处理方案
- javascript - 将布尔值传递给另一个 Angular 组件
- c++ - 用不同的整数组装 char 数组以模拟日期和时间