创建两个线程实现奇数和偶数的交替输出Java代码
时间: 2024-11-03 15:15:40 浏览: 20
java代码-三个线程轮流输出abc
创建两个线程在Java中交替输出奇数和偶数可以使用`Thread`类、`Runnable`接口或者`Callable`接口配合`FutureTask`。这里我将展示如何使用`Runnable`接口的示例:
```java
import java.util.concurrent.*;
public class OddEvenThread {
private int number = 0;
private final Object lock = new Object(); // 用于同步两个线程
public class OddThread implements Runnable {
@Override
public void run() {
while (true) {
synchronized (lock) {
if (number % 2 == 0) { // 如果是偶数,其他线程会先持有锁,跳过打印
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else { // 打印奇数并唤醒等待的偶数线程
System.out.println(Thread.currentThread().getName() + ": " + number++);
lock.notifyOne(); // 唤醒等待的线程
}
}
}
}
}
public class EvenThread extends OddThread implements Runnable {
@Override
public void run() {
while (true) {
synchronized (lock) {
if (number % 2 != 0) { // 如果是奇数,打印并唤醒等待的奇数线程
System.out.println(Thread.currentThread().getName() + ": " + number++);
lock.notifyOne(); // 唤醒等待的线程
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new OddEvenThread().new OddThread());
executor.execute(new OddEvenThread().new EvenThread());
executor.shutdown();
}
}
阅读全文