Java 线程在开始运行之前的状态不是新的,它是可运行的,不是吗
从基础学习开始,我对Java中的线程一无所知,我知道当创建线程时,它处于新状态。当线程处于此状态时,该线程尚未开始运行Java 线程在开始运行之前的状态不是新的,它是可运行的,不是吗,java,multithreading,Java,Multithreading,从基础学习开始,我对Java中的线程一无所知,我知道当创建线程时,它处于新状态。当线程处于此状态时,该线程尚未开始运行 public class MainClassForThread { public static void main(String[] args) { // TODO Auto-generated method stub Thread t1 = new ExtendingThreadClass(); Thread t2 =
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());
}
}
}
问题在于这一行:
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());
您将获得当前线程的状态,该线程正在运行。显然。如果您阅读文档,即的javadoc,它说返回对当前正在执行的线程对象的引用,那么当方法被显式地记录为返回对正在执行的线程的引用时,为什么您会对线程正在运行感到困惑呢,请注意警告,不要从实例调用静态方法。@shmosel您假设OP使用IDE甚至可以看到警告。
System.out.println("Before start of thread the state of thread is " + t1.getState());