分别使用两种创建线程的方法,打印1-1000之间的奇数和偶数
时间: 2024-11-20 08:41:17 浏览: 8
C++11用两个线程轮流打印整数的实现方法
在Java中,可以使用两种常见的方法来创建线程并同时打印1-1000范围内的奇数和偶数:
1. **匿名内部类(Thread 实现 Runnable 接口)**:
```java
class PrintNumbers implements Runnable {
private boolean isOdd;
public PrintNumbers(boolean isOdd) {
this.isOdd = isOdd;
}
@Override
public void run() {
for (int i = 1; i <= 1000; i++) {
if ((isOdd && i % 2 != 0) || (!isOdd && i % 2 == 0)) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
}
public class Main {
public static void main(String[] args) {
Thread oddThread = new Thread(new PrintNumbers(true), "Odd");
Thread evenThread = new Thread(new PrintNumbers(false), "Even");
oddThread.start();
evenThread.start();
try {
oddThread.join();
evenThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们创建了两个`PrintNumbers`线程,一个负责打印奇数,另一个打印偶数。
2. **实现 `Callable` 接口**:
```java
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class PrintNumbersCallable implements Callable<Integer> {
private int start;
public PrintNumbersCallable(int start, boolean isOdd) {
this.start = start;
}
@Override
public Integer call() throws Exception {
for (int i = start; i <= 1000; i++) {
if ((isOdd && i % 2 != 0) || (!isOdd && i % 2 == 0)) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
return null;
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<?> futureOdd = executor.submit(new PrintNumbersCallable(1, true), "Odd");
Future<?> futureEven = executor.submit(new PrintNumbersCallable(2, false), "Even");
executor.shutdown();
try {
futureOdd.get(); // 等待任务完成
futureEven.get(); // 等待另一个任务完成
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}
}
```
这里我们使用了`ExecutorService`和`Future`来异步地提交任务,并等待它们完成。
阅读全文