用Java写一段代码,实现一个线程输出{1.3.5.7},一个线程输出{2.4.6.8},两个线程交替输出{1.2.3.4.5.6.7.8}
时间: 2024-05-05 09:20:13 浏览: 7
```
public class AlternatePrinting {
private static Object lock = new Object();
private static int count = 1;
private static int maxCount = 8;
public static void main(String[] args) {
new Thread(() -> {
synchronized (lock) {
while (count <= maxCount) {
if (count % 2 != 0) {
System.out.print(count + " ");
count++;
}
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}).start();
new Thread(() -> {
synchronized (lock) {
while (count <= maxCount) {
if (count % 2 == 0) {
System.out.print(count + " ");
count++;
}
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}).start();
}
}
```