写两个线程一个输出偶数一个输出奇数Java
时间: 2024-12-14 08:19:42 浏览: 14
在Java中,你可以创建两个线程分别处理打印奇数和偶数的任务。这里是一个简单的例子,使用`Thread`类和`synchronized`关键字来防止竞态条件:
```java
public class PrintNumber {
private static int counter = 0;
private static final Object lock = new Object();
public class OddThread extends Thread {
@Override
public void run() {
while (true) {
synchronized (lock) {
if (counter % 2 != 0) {
System.out.println(Thread.currentThread().getName() + ": " + (counter++));
lock.notify();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class EvenThread extends Thread {
@Override
public void run() {
while (true) {
synchronized (lock) {
if (counter % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ": " + (counter++));
lock.notify();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args) {
OddThread oddThread = new OddThread();
EvenThread evenThread = new EvenThread();
oddThread.start();
evenThread.start();
}
}
阅读全文