编写应用程序,在主线程中再创建2个线程,要求线程经历4种状态:新建、运行、中断、死亡。 java
时间: 2024-12-15 15:19:19 浏览: 17
在Java中,你可以使用`Thread`类和`Runnable`接口来创建线程,并通过`Thread`的生命周期来观察线程的不同状态。下面是一个简单的示例程序,展示了线程从新建到死亡的四种状态:
```java
public class Main {
public static void main(String[] args) {
// 创建主线程
Thread.currentThread().setName("Main Thread");
System.out.println("Main Thread: State - New");
// 创建并启动两个工作线程
Thread thread1 = createThread("Thread 1");
startThread(thread1);
System.out.println("Main Thread: Thread 1 started, State - Running");
Thread thread2 = createThread("Thread 2");
startThread(thread2);
System.out.println("Main Thread: Thread 2 started, State - Running");
// 中断线程2
interruptThread(thread2);
System.out.println("Main Thread: Interrupting Thread 2, State - Interrupted");
// 等待线程2退出
joinThread(thread2);
System.out.println("Main Thread: Thread 2 joined, State - Dead");
// 线程1现在是唯一活动的,但它不会立即结束
try {
joinThread(thread1); // 这里需要加入try-catch块来处理InterruptedException
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main Thread: Thread 1 joined, State - Dead");
}
private static Thread createThread(String name) {
return new Thread(() -> {
while (true) {
System.out.printf("%s: Sleeping in a loop...%n", name);
try {
Thread.sleep(1000); // 模拟线程运行
} catch (InterruptedException e) {
break;
}
}
System.out.println(name + ": Exiting loop");
}, name);
}
private static void startThread(Thread thread) {
thread.start();
}
private static void interruptThread(Thread thread) {
thread.interrupt(); // 设置线程中断标志
}
private static void joinThread(Thread thread) throws InterruptedException {
thread.join(); // 主线程等待线程执行完毕
}
}
```
在这个程序中,每个新创建的线程会进入`RUNNING`状态,当我们调用`interrupt()`方法时,线程会进入`INTERRUPTED`状态。接着主线程调用`join()`方法等待线程结束,这使得线程处于`DEAD`状态。当主线程也结束时,整个应用也随之关闭。
阅读全文