同时启动2个线程,一个线程打印A,一个线程打印B,实现ABAB这样轮流打印,每个线程打印10次,用java如何实现?
时间: 2024-04-10 19:28:10 浏览: 13
在Java中,您可以使用多线程的方式来实现ABAB轮流打印。下面是一个使用Java的示例代码:
```java
class PrintThread implements Runnable {
private String message;
private int count;
public PrintThread(String message, int count) {
this.message = message;
this.count = count;
}
public void run() {
for (int i = 0; i < count; i++) {
System.out.print(message);
Thread.yield(); // 可选,用于让出CPU时间片
}
}
}
public class Main {
public static void main(String[] args) {
Thread threadA = new Thread(new PrintThread("A", 10));
Thread threadB = new Thread(new PrintThread("B", 10));
threadA.start();
threadB.start();
try {
threadA.join();
threadB.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们创建了一个`PrintThread`类实现`Runnable`接口,用于打印指定的消息。在`run()`方法中,使用一个循环打印指定次数的消息,并使用`Thread.yield()`方法(可选)让出CPU时间片。
在`Main`类中,我们创建了两个线程`threadA`和`threadB`,分别用于打印字母A和B。每个线程循环打印10次,通过调用`start()`方法启动线程,然后通过`join()`方法等待线程执行完毕。
运行以上代码,您将会看到输出结果为`ABABABABABABABABABAB`,即实现了ABAB轮流打印的效果。