用Java写一个代码,编写一个程序,创建两个线程,要求分别输出26个字母。在输出结果时,要显示是哪个线程输出的字母。
时间: 2024-03-07 20:47:57 浏览: 23
好的,以下是Java代码:
```java
public class TwoThreadsPrintAlphabets {
public static void main(String[] args) {
Thread t1 = new Thread(new PrintAlphabetsTask("Thread 1"));
Thread t2 = new Thread(new PrintAlphabetsTask("Thread 2"));
t1.start();
t2.start();
}
}
class PrintAlphabetsTask implements Runnable {
private String threadName;
private int startChar = 65; // ASCII码中 A 的值
private int endChar = 90; // ASCII码中 Z 的值
public PrintAlphabetsTask(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
for (int i = startChar; i <= endChar; i++) {
System.out.println(threadName + ": " + (char) i);
}
}
}
```
这段代码会创建两个线程,分别输出 A 到 Z 的字母,并且在输出结果时会显示是哪个线程输出的字母。其中,线程名由构造函数传入,字母的输出使用 ASCII 码来处理。