Files
article/java/线程.md
2025-07-21 20:59:36 +08:00

70 lines
2.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

```
import java.util.concurrent.atomic.AtomicInteger;
public class AlternatePrint {
// 使用原子整数作为共享变量初始值为1表示轮到线程1打印第一个数字
private static AtomicInteger turn = new AtomicInteger(1);
// 当前要打印的数字
private static int currentNumber = 1;
// 定义终止条件
private static final int MAX_NUMBER = 100;
public static void main(String[] args) {
// 创建两个线程
Thread thread1 = new Thread(() -> {
while (currentNumber <= MAX_NUMBER) {
// 线程1检查是否轮到自己
if (turn.get() == 1) {
System.out.println("线程1: " + currentNumber);
// 切换到线程2
turn.set(2);
}
// 短暂休眠以避免CPU过度使用
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
});
Thread thread2 = new Thread(() -> {
while (currentNumber <= MAX_NUMBER) {
// 线程2检查是否轮到自己
if (turn.get() == 2) {
System.out.println("线程2: " + currentNumber);
// 增加当前数字
currentNumber++;
// 切换回线程1
turn.set(1);
}
// 短暂休眠
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
});
// 启动线程
thread1.start();
thread2.start();
// 等待线程结束
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("所有数字打印完毕");
}
}
```