分别使用两种创建线程的方法吗,打印1-1000之间的奇数和偶数java
时间: 2024-10-27 12:14:50 浏览: 27
java用线程两种方式
在Java中,你可以使用两种常见的方法来创建线程:继承Thread类和实现Runnable接口。以下是两种方法分别用于打印1到1000之间奇数和偶数的示例:
1. **通过继承Thread类**:
```java
public class OddEvenThread extends Thread {
private int start, end;
public OddEvenThread(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
if (i % 2 == 0) {
System.out.println("偶数:" + i);
} else {
System.out.println("奇数:" + i);
}
}
}
public static void main(String[] args) {
Thread oddThread = new OddEvenThread(1, 500);
Thread evenThread = new OddEvenThread(501, 1000);
oddThread.start(); // 启动奇数线程
evenThread.start(); // 启动偶数线程
}
}
```
2. **通过实现Runnable接口**:
```java
public class PrintOddEven implements Runnable {
private int start, end;
public PrintOddEven(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
if (i % 2 == 0) {
System.out.println("偶数:" + i);
} else {
System.out.println("奇数:" + i);
}
}
}
public static void main(String[] args) {
Thread oddThread = new Thread(new PrintOddEven(1, 500));
Thread evenThread = new Thread(new PrintOddEven(501, 1000));
oddThread.start();
evenThread.start();
}
}
```
在这两个例子中,我们创建了两个线程,一个打印1-500范围内的偶数,另一个打印501-1000范围内的奇数。每个线程在其run()方法中独立执行任务。
阅读全文