java 创建多个线程 并等待线程关闭
时间: 2023-11-28 13:43:18 浏览: 29
以下是Java创建多个线程并等待线程关闭的示例代码:
```java
public class MyThread extends Thread {
private int threadId;
public MyThread(int id) {
this.threadId = id;
}
public void run() {
System.out.println("Thread " + threadId + " is running.");
try {
Thread.sleep(5000); // 模拟线程执行时间
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread " + threadId + " is finished.");
}
}
public class Main {
public static void main(String[] args) {
int numThreads = 5;
MyThread[] threads = new MyThread[numThreads];
// 创建并启动多个线程
for (int i = 0; i < numThreads; i++) {
threads[i] = new MyThread(i);
threads[i].start();
}
// 等待所有线程执行完毕
for (int i = 0; i < numThreads; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("All threads are finished.");
}
}
```
在上面的示例中,我们首先定义了一个`MyThread`类,它继承自`Thread`类,并实现了`run()`方法。在`run()`方法中,我们打印出线程的ID,然后让线程休眠5秒钟,最后再打印出线程的ID表示线程已经执行完毕。
在`Main`类中,我们首先创建了一个包含5个`MyThread`对象的数组,并启动了所有线程。然后,我们使用`join()`方法等待所有线程执行完毕。最后,我们打印出一条消息表示所有线程都已经执行完毕。