Java 线程创建中 NEW 状态是什么意思
new 状态表示线程对象已经被实例化,但尚未启动执行。在 java 中,当你使用 new 关键字创建一个 thread 对象时,该线程就处于 new 状态。此时线程还没有被调度器接管,也没有开始运行任何代码。

如何从 NEW 状态进入 RUNNABLE 状态
调用 Thread 对象的 start() 方法可以将线程从 NEW 状态转换为 RUNNABLE 状态。start() 方法会通知 JVM 分配必要的资源并启动新线程的执行。

public class NewStateExample {
public static void main(String[] args) {
// 创建线程对象,此时处于 NEW 状态
Thread thread = new Thread(() -> {
System.out.println("Thread is running");
});
// 检查初始状态
System.out.println("Initial state: " + thread.getState());
// 调用 start() 方法,线程进入 RUNNABLE 状态
thread.start();
// 等待线程启动后检查状态
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 检查启动后的状态
System.out.println("After start: " + thread.getState());
}
}
NEW 状态下可以执行哪些操作
在 NEW 状态下,可以对线程对象进行配置操作,如设置名称、优先级和守护进程属性等。这些操作不会改变线程的状态,只是为线程的后续执行做准备。

public class NewStateOperations {
public static void main(String[] args) {
// 创建线程对象
Thread thread = new Thread(() -> {
System.out.println("Thread executing");
});
// 在 NEW 状态下设置线程属性
thread.setName("MyThread");
thread.setPriority(Thread.MAX_PRIORITY);
thread.setDaemon(true);
// 验证设置是否生效
System.out.println("Thread name: " + thread.getName());
System.out.println("Thread priority: " + thread.getPriority());
System.out.println("Is daemon: " + thread.isDaemon());
System.out.println("Current state: " + thread.getState());
// 启动线程
thread.start();
}
}
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











