编程:创建两个线程,要求如下: (1)一个线程输出1~26,另一个线程输出A~Z(2)一个线程使用继承Thread类的写法,另一个线程 使用实现Runnable接口的写法 用java
时间: 2024-11-22 10:28:45 浏览: 4
在Java中,你可以按照以下步骤创建两个线程,分别满足你的需求:
1. **继承Thread类的写法**:
```java
public class PrintNumbers extends Thread {
private int number;
public PrintNumbers(int start) {
this.number = start;
}
@Override
public void run() {
for (int i = 1; i <= 26; i++) {
System.out.print(Thread.currentThread().getName() + ": " + (char) ('a' + i - 1));
if (i % 5 == 0) {
try {
// 每打印5个字符暂停一下
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
PrintNumbers thread1 = new PrintNumbers(1);
PrintNumbers thread2 = new PrintNumbers('A');
thread1.start(); // 输出数字1到26
thread2.start(); // 输出字母A到Z
}
}
```
2. **实现Runnable接口的写法**:
```java
public class PrintAlphabets implements Runnable {
private char letter;
public PrintAlphabets(char start) {
this.letter = start;
}
@Override
public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(Thread.currentThread().getName() + ": " + c);
if (c == 'Z') {
break; // 打印完字母Z就结束
}
}
}
public static void main(String[] args) {
Thread printNumbersThread = new Thread(new PrintNumbersTask(1));
Thread printAlphabetsThread = new Thread(new PrintAlphabetsTask('A'));
printNumbersThread.start();
printAlphabetsThread.start();
}
// 使用匿名内部类实现Runnable接口
private static class PrintNumbersTask implements Runnable {
private int number;
public PrintNumbersTask(int start) {
number = start;
}
@Override
public void run() {
for (int i = 1; i <= 26; i++) {
System.out.print(Thread.currentThread().getName() + ": " + (char) ('a' + i - 1));
if (i % 5 == 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
```
这两个例子展示了如何分别通过继承`Thread`和实现`Runnable`接口的方式来创建并启动两个线程。每个线程会按指定顺序打印数字和字母。
阅读全文