方案一使用锁:
通过synchronized和wait/notify机制实现线程同步:
创建了两个线程,通过共享锁对象和计数器实现交替打印。奇数由Thread-1打印,偶数由Thread-2打印,使用wait/notify进行线程间通信。
public class AlternatePrint {
private static final Object lock = new Object();
private static int count = 1;
private static final int MAX = 100;
public static void main(String[] args) {
new Thread(() -> {
while (count <= MAX) {
synchronized (lock) {
if (count % 2 == 1) {
System.out.println(Thread.currentThread().getName() + ": " + count++);
//唤醒在此对象锁上等待的单个线程
lock.notify();
} else {
try {
//释放锁并等待
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}, "Thread-1").start();
new Thread(() -> {
while (count <= MAX) {
synchronized (lock) {
if (count % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ": " + count++);
lock.notify();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}, "Thread-2").start();
}
}
两个线程在不加锁的情况下按顺序交叉打印1-100数字:
在不加锁的情况下,可以使用 volatile
变量和 yield()
实现两个线程交替打印 1-100 的数字。
使用 volatile
可以确保 count
的可见性,并通过 Thread.yield()
让出 CPU 时间片。但这种方式效率较低,适合轻量级任务。
public class AlternatePrintWithoutLock {
private static volatile int count = 1;
private static final int MAX = 100;
public static void main(String[] args) {
new Thread(() -> {
while (count <= MAX) {
if (count % 2 == 1) {
System.out.println(Thread.currentThread().getName() + ": " + count++);
} else {
//主动让出 CPU:当前线程从运行状态(RUNNING)转为就绪状态(RUNNABLE),允许其他同优先级线程执行
Thread.yield();
}
}
}, "Thread-1").start();
new Thread(() -> {
while (count <= MAX) {
if (count % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ": " + count++);
} else {
Thread.yield();
}
}
}, "Thread-2").start();
}
}