设置两个线程A和B,线程A打印1-26,线程B打印A-Z,要求每隔1秒交替打印
时间: 2024-12-06 13:33:26 浏览: 17
要实现这个需求,可以使用Java的`Thread`类、`Runnable`接口以及`synchronized`关键字来保证线程同步,防止交替打印的顺序混乱。以下是简单的代码示例:
```java
class Printer implements Runnable {
private final String sequence;
private int index = 0;
private boolean isNext;
public Printer(String sequence, boolean isFirst) {
this.sequence = sequence;
this.isNext = isFirst;
}
@Override
public void run() {
while (true) {
synchronized (this) {
if (index < sequence.length()) {
printCharacter();
if (!isNext) { // 切换到另一个线程
try {
wait(1000); // 等待1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
isNext = !isNext; // 交换当前线程是否先打印
}
} else {
break; // 打印完毕,退出循环
}
}
}
}
private void printCharacter() {
System.out.print(sequence.charAt(index++));
}
}
public class Main {
public static void main(String[] args) {
Printer threadA = new Printer("1-26", true);
Printer threadB = new Printer("A-Z", false);
Thread t1 = new Thread(threadA, "Thread A");
Thread t2 = new Thread(threadB, "Thread B");
t1.start(); // 线程A先开始
t2.start();
try {
t1.join(); // 确保线程A完成后再结束main
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,线程A和线程B都实现了`Printer`接口,分别负责打印各自的序列。通过`synchronized`和`wait()`/`notify()`机制,确保了交替打印的每一步操作。
阅读全文