线程交叉打印
- User
线程交叉打印
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
线程交叉打印
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
线程交叉打印是一个经典的多线程同步问题,常见场景包括:
下面分别用 synchronized、Lock、Semaphore、Atomic 等方式实现这些场景。
目标:线程1打印奇数(1, 3, 5...),线程2打印偶数(2, 4, 6...)。
public class OddEvenPrinter {
private static final Object lock = new Object();
private static volatile boolean isOddTurn = true; // 标记当前该谁打印
private static final int MAX = 10; // 打印到10
public static void main(String[] args) {
new Thread(() -> printOdd(), "奇数线程").start();
new Thread(() -> printEven(), "偶数线程").start();
}
static void printOdd() {
for (int i = 1; i <= MAX; i += 2) {
synchronized (lock) {
while (!isOddTurn) { // 不是奇数线程的轮次,等待
try { lock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
System.out.println(Thread.currentThread().getName() + ": " + i);
isOddTurn = false; // 切换到偶数线程
lock.notify(); // 唤醒偶数线程
}
}
}
static void printEven() {
for (int i = 2; i <= MAX; i += 2) {
synchronized (lock) {
while (isOddTurn) { // 不是偶数线程的轮次,等待
try { lock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
System.out.println(Thread.currentThread().getName() + ": " + i);
isOddTurn = true; // 切回奇数线程
lock.notify(); // 唤醒奇数线程
}
}
}
}
运行结果:
奇数线程: 1
偶数线程: 2
奇数线程: 3
偶数线程: 4
奇数线程: 5
偶数线程: 6
...
原理:
isOddTurn 标记当前该谁打印。wait() 让当前线程等待,notify() 唤醒另一个线程。synchronized 确保同一时刻只有一个线程操作共享变量。更灵活的线程通信方式:
import java.util.concurrent.locks.*;
public class OddEvenPrinter_Lock {
private static final Lock lock = new ReentrantLock();
private static final Condition oddCond = lock.newCondition();
private static final Condition evenCond = lock.newCondition();
private static volatile boolean isOddTurn = true;
private static final int MAX = 10;
public static void main(String[] args) {
new Thread(() -> printOdd(), "奇数线程").start();
new Thread(() -> printEven(), "偶数线程").start();
}
static void printOdd() {
for (int i = 1; i <= MAX; i += 2) {
lock.lock();
try {
while (!isOddTurn) oddCond.await(); // 等待偶数线程唤醒
System.out.println(Thread.currentThread().getName() + ": " + i);
isOddTurn = false;
evenCond.signal(); // 通知偶数线程
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
finally { lock.unlock(); }
}
}
static void printEven() {
for (int i = 2; i <= MAX; i += 2) {
lock.lock();
try {
while (isOddTurn) evenCond.await(); // 等待奇数线程唤醒
System.out.println(Thread.currentThread().getName() + ": " + i);
isOddTurn = true;
oddCond.signal(); // 通知奇数线程
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
finally { lock.unlock(); }
}
}
}
优势:
Condition 比 wait/notify 更灵活(可创建多个等待队列)。oddCond.signal() 只唤醒奇数线程)。目标:线程A打印"A",线程B打印"B",交替进行。
Semaphore(信号量)控制许可数量,非常适合交替场景:
import java.util.concurrent.Semaphore;
public class ABPrinter {
private static final Semaphore semA = new Semaphore(1); // A先执行
private static final Semaphore semB = new Semaphore(0); // B初始无许可
public static void main(String[] args) {
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
semA.acquire(); // A获取许可
System.out.print("A");
semB.release(); // 释放B的许可
}
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}, "线程A").start();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
semB.acquire(); // B等待许可
System.out.print("B");
semA.release(); // 释放A的许可
}
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}, "线程B").start();
}
}
输出:
ABABABABAB...
原理:
semA 初始1个许可,semB 初始0个。semA.acquire() → 打印A → semB.release()。目标:线程1打印"A",线程2打印"B",线程3打印"C",循环N次。
import java.util.concurrent.locks.*;
public class ABCPrinter {
private static final Lock lock = new ReentrantLock();
private static final Condition condA = lock.newCondition();
private static final Condition condB = lock.newCondition();
private static final Condition condC = lock.newCondition();
private static int state = 1; // 1:A, 2:B, 3:C
private static final int LOOP = 5; // 循环5次
public static void main(String[] args) {
new Thread(() -> print("A", 1, condA, condB), "线程A").start();
new Thread(() -> print("B", 2, condB, condC), "线程B").start();
new Thread(() -> print("C", 3, condC, condA), "线程C").start();
}
static void print(String name, int targetState, Condition currentCond, Condition nextCond) {
for (int i = 0; i < LOOP; i++) {
lock.lock();
try {
while (state != targetState) currentCond.await(); // 等待自己的轮次
System.out.print(name);
state = (state % 3) + 1; // A→B→C→A
nextCond.signal(); // 唤醒下一个线程
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
finally { lock.unlock(); }
}
}
}
输出:
ABCABCABCABCABC
逻辑:
state = 1 时,A打印,改 state = 2 并唤醒B。state = 2,打印B,改 state = 3 并唤醒C。state = 1,再唤醒A。| 方法 | 优点 | 缺点 |
|---|---|---|
| synchronized + wait/notify | 简单、原生支持 | 唤醒所有线程,效率低 |
| Lock + Condition | 精确唤醒、更灵活 | 代码稍复杂 |
| Semaphore | 简单直观,适合交替场景 | 需理解许可机制 |
| Atomic + 自旋 | 无锁化,性能高 | 耗CPU(忙等待) |
选择建议:
这些代码可以直接运行,试试修改 MAX 或 LOOP 值,感受多线程的协同工作!😄