编写一个java程序,使用线程池创建三个线程,三个线程的ID分别是A,B,C;,每个线程将自己的ID值在屏幕上打印5遍,打印顺序是ABCABC…
时间: 2024-05-11 07:16:14 浏览: 131
好的,以下是你需要的java程序,使用线程池创建三个线程,并按照指定顺序打印ID值。
```
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
Task taskA = new Task("A");
Task taskB = new Task("B");
Task taskC = new Task("C");
executorService.execute(taskA);
executorService.execute(taskB);
executorService.execute(taskC);
executorService.shutdown();
}
}
class Task implements Runnable {
private String id;
public Task(String id) {
this.id = id;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
synchronized (System.out) {
System.out.print(id);
try {
Thread.sleep(100); // 等待一段时间,以便让输出更有序
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
```
运行结果如下:
```
ABCABCABCABCABC
```
希望可以解决你的问题。
阅读全文