java代码,创建两个线程,一个线程打印英文字母“A”-“z”,一个打印0-100。两种方式都要实现。
时间: 2024-03-10 14:45:54 浏览: 52
方式一:使用继承Thread类的方式实现
```
public class PrintLetters extends Thread {
@Override
public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
}
}
}
public class PrintNumbers extends Thread {
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
System.out.print(i + " ");
}
}
}
public class Main {
public static void main(String[] args) {
PrintLetters printLetters = new PrintLetters();
PrintNumbers printNumbers = new PrintNumbers();
printLetters.start();
printNumbers.start();
}
}
```
方式二:使用实现Runnable接口的方式实现
```
public class PrintLetters implements Runnable {
@Override
public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
}
}
}
public class PrintNumbers implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
System.out.print(i + " ");
}
}
}
public class Main {
public static void main(String[] args) {
PrintLetters printLetters = new PrintLetters();
PrintNumbers printNumbers = new PrintNumbers();
Thread thread1 = new Thread(printLetters);
Thread thread2 = new Thread(printNumbers);
thread1.start();
thread2.start();
}
}
```
阅读全文