JAVA创建一个线程完成五个字符串的循环显示
时间: 2023-08-20 15:04:01 浏览: 55
好的,下面是一个JAVA的示例代码,实现创建一个线程完成五个字符串的循环显示:
```java
public class StringThread implements Runnable {
private String string;
private int num;
public StringThread(String string, int num) {
this.string = string;
this.num = num;
}
public void run() {
for (int i = 0; i < num; i++) {
System.out.println(string);
}
}
public static void main(String[] args) {
String[] strings = {"Hello", "World", "Java", "Thread", "Programming"};
int num = 3;
Thread[] threads = new Thread[strings.length];
// 创建线程并启动
for (int i = 0; i < strings.length; i++) {
StringThread st = new StringThread(strings[i], num);
threads[i] = new Thread(st);
threads[i].start();
}
// 等待所有线程结束
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
这段代码会创建五个线程,每个线程负责显示一个字符串,循环显示三次。您可以根据需要修改字符串数组和循环次数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)