Java编写程序,创建并运行3个线程:第一个线程打印100次字母a,第二个线程打印100次字母b,第三个线程打印1~100的整数。
时间: 2023-09-19 14:10:50 浏览: 87
下面是Java代码实现:
```java
public class MultiThreadExample {
public static void main(String[] args) {
Thread threadA = new Thread(new PrintLetterTask('a', 100));
Thread threadB = new Thread(new PrintLetterTask('b', 100));
Thread threadC = new Thread(new PrintNumberTask(100));
threadA.start();
threadB.start();
threadC.start();
}
}
class PrintLetterTask implements Runnable {
private char letter;
private int times;
public PrintLetterTask(char letter, int times) {
this.letter = letter;
this.times = times;
}
@Override
public void run() {
for (int i = 0; i < times; i++) {
System.out.print(letter);
}
}
}
class PrintNumberTask implements Runnable {
private int times;
public PrintNumberTask(int times) {
this.times = times;
}
@Override
public void run() {
for (int i = 1; i <= times; i++) {
System.out.print(i + " ");
}
}
}
```
上面的代码中,我们创建了一个 `MultiThreadExample` 类作为程序的入口,其中创建了三个线程:`threadA`、`threadB`、`threadC`。分别代表打印字母a、打印字母b、打印数字的线程。
`PrintLetterTask` 类和 `PrintNumberTask` 类都实现了 `Runnable` 接口,重写了 `run()` 方法,分别代表线程的执行任务。在 `run()` 方法中,通过循环打印指定次数的字母或数字。
最后,我们启动三个线程,分别执行任务。执行结果可能是这样的:
```
aabb12345678910b1112aabb1314151617b1819aabb2021222324b2526aabb2728293031b3233aabb3435363738b3940aabb4142434445b4647aabb4849505152b5354aabb5556575859b6061aabb6263646566b6768aabb6970717273b7475aabb7677787980b8182aabb8384858687b8889aabb9091929394b9596aabb979899100b
```
阅读全文