编程实现,创建两个线程,两个线程都循环输出10次,每次输出一行。一个线程输出0~9的随机数,每行输出10个;另一个线程输出字母a~z,每行输出26个。
时间: 2024-12-24 13:35:53 浏览: 3
在Java中,我们可以使用`Thread`类和`synchronized`关键字来实现这个场景。下面是一个简单的示例,展示了如何创建两个线程,分别输出数字和字母:
```java
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class MultiThreadExample {
private static final AtomicInteger lineCounter = new AtomicInteger(0);
private static final int MAX_LINES = 10;
private static final int NUM_DIGITS = 10;
private static final char[] ALPHABET = 'a' - 'A' + '0';
public static void main(String[] args) {
Thread randomThread = new Thread(() -> printRandomNumbers());
Thread alphabetThread = new Thread(() -> printAlphabet());
randomThread.start();
alphabetThread.start();
try {
randomThread.join(); // 等待randomThread完成
alphabetThread.join(); // 然后再等待alphabetThread完成
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static synchronized void printRandomNumbers() {
while (lineCounter.getAndIncrement() < MAX_LINES) {
System.out.println(getRandomLine(NUM_DIGITS));
}
}
private static synchronized void printAlphabet() {
while (lineCounter.getAndIncrement() < MAX_LINES) {
System.out.println(getAlphabetLine());
}
}
private static String getRandomLine(int numDigits) {
Random random = new Random();
StringBuilder line = new StringBuilder();
for (int i = 0; i < 10; i++) {
line.append(random.nextInt(NUM_DIGITS)).append(' ');
}
return line.toString();
}
private static String getAlphabetLine() {
StringBuilder line = new StringBuilder();
for (char c : ALPHABET) {
if (line.length() == 26) {
break;
}
line.append(c);
}
return line.toString();
}
}
阅读全文