创建两个线程,要求如下: (1)一个线程输出100个1~26,另一个线程输出100个A~Z。 (2)一个线程使用集成Thread 类的写法,另一个线程使用实现Runnable接口的写法。 输出格式: 每一行输出一个1~26数字或者是A~Z的字符
时间: 2024-11-22 16:22:03 浏览: 32
创建两个线程分别输出1到26的数字和大写字母A到Z可以按照以下步骤实现:
**使用`Thread`类的例子**:
```java
public class PrintNumbers implements Runnable {
private int num;
public PrintNumbers(int num) {
this.num = num;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println(i);
}
System.out.println("Number thread completed.");
}
}
public class PrintLetters extends Thread {
private char letter;
public PrintLetters(char letter) {
this.letter = letter;
}
@Override
public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c);
}
System.out.println("\nLetter thread completed.");
}
}
public class Main {
public static void main(String[] args) {
PrintNumbers numbersThread = new PrintNumbers(0); // 由于PrintNumbers需要一个整数作为构造参数,这里随便填了一个0
PrintLetters lettersThread = new PrintLetters('A');
numbersThread.start(); // 启动数字线程
lettersThread.start(); // 同样启动字母线程
}
}
```
**使用`Runnable`接口的例子**:
```java
public class NumberPrinter implements Runnable {
private int num;
public NumberPrinter(int num) {
this.num = num;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println(i);
}
System.out.println("Number thread completed.");
}
}
public class LetterPrinter implements Runnable {
private char letter;
public LetterPrinter(char letter) {
this.letter = letter;
}
@Override
public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c);
}
System.out.println("\nLetter thread completed.");
}
}
public class Main {
public static void main(String[] args) {
Thread numbersThread = new Thread(new NumberPrinter(0)); // 使用匿名内部类传递给Thread
Thread lettersThread = new Thread(new LetterPrinter('A'));
numbersThread.start();
lettersThread.start();
}
}
```
这两个例子中,每个线程都有自己的任务,通过`start()`方法启动。注意,如果要在Java中创建线程,通常推荐使用`Runnable`接口而不是直接继承`Thread`类,因为`Thread`类只能有一个实例方法`run()`,而`Runnable`接口允许提供多个实现。
阅读全文