在Java中,可以使用synchronized
關鍵字和wait()
、notify()
方法來實現多線程交替打印奇偶數。下面是一個簡單的示例:
public class AlternatePrinting {
private static final Object lock = new Object();
private static int count = 1;
public static void main(String[] args) {
Thread oddThread = new Thread(new OddNumberPrinter(), "OddThread");
Thread evenThread = new Thread(new EvenNumberPrinter(), "EvenThread");
oddThread.start();
evenThread.start();
}
static class OddNumberPrinter implements Runnable {
@Override
public void run() {
while (count <= 100) {
synchronized (lock) {
if (count % 2 == 1) {
System.out.println(Thread.currentThread().getName() + ": " + count++);
lock.notify();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
static class EvenNumberPrinter implements Runnable {
@Override
public void run() {
while (count <= 100) {
synchronized (lock) {
if (count % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ": " + count++);
lock.notify();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
在這個示例中,我們創建了兩個線程:oddThread
和evenThread
。oddThread
負責打印奇數,evenThread
負責打印偶數。它們共享一個鎖對象lock
和一個靜態變量count
。
當count
為奇數時,oddThread
獲取鎖并打印數字,然后增加count
并調用lock.notify()
喚醒等待的線程。接著,oddThread
調用lock.wait()
釋放鎖并進入等待狀態。
當count
為偶數時,evenThread
的行為與oddThread
類似。
這樣,兩個線程就可以交替打印奇偶數了。