首页 > 解决方案 > 运行开始前的线程状态不是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

标签: javamultithreading

解决方案


问题是这一行:

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());

推荐阅读