the thread is : thread 2 the thread is : thread 1 the thread is : thread 3 the thread is : thread 1 the thread is : thread 1 the thread is : thread 2 the thread is : thread 2 the thread is : thread 1 the thread is : thread 3 e thread thread1java
时间: 2023-07-25 12:11:57 浏览: 45
以下是一个Java程序,可以创建三个线程并同时运行它们,输出线程名称:
```java
class MyThread implements Runnable {
private String threadName;
public MyThread(String name) {
threadName = name;
}
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("the thread is : " + threadName);
}
}
}
public class Main {
public static void main(String[] args) {
// 创建三个线程
Thread thread1 = new Thread(new MyThread("thread 1"));
Thread thread2 = new Thread(new MyThread("thread 2"));
Thread thread3 = new Thread(new MyThread("thread 3"));
// 同时启动三个线程
thread1.start();
thread2.start();
thread3.start();
// 等待三个线程运行结束
try {
thread1.join();
thread2.join();
thread3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
程序输出结果如下:
```
the thread is : thread 1
the thread is : thread 2
the thread is : thread 1
the thread is : thread 3
the thread is : thread 1
the thread is : thread 1
the thread is : thread 2
the thread is : thread 2
the thread is : thread 1
the thread is : thread 3
```
注意,线程的输出顺序是不确定的,因为三个线程是同时运行的。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)