三个线程交替打印ABC
public class PrintABC {
private static final Object lock = new Object();
private static volatile Integer index = 0;
private static final int count = 3;
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (index % count != 0) {
try {
lock.wait();
} catch (InterruptedException e) {
}
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
System.out.print(i + "A");
index++;
lock.notifyAll();
}
}
}, "a-thread");
Thread t2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (index % count != 1) {
try {
lock.wait();
} catch (InterruptedException e) {
}
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
System.out.print("B");
index++;
lock.notifyAll();
}
}
}, "b-thread");
Thread t3 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (index % count != 2) {
try {
lock.wait();
} catch (InterruptedException e) {
}
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
System.out.print("C");
index++;
lock.notifyAll();
}
}
}, "c-thread");
t3.start();
t2.start();
t1.start();
}
}
使用ReentrantLock的队列实现的版本
public class PrintABC2 {
private static volatile Integer COUNT = 0;
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
Thread t1 = new Thread(() -> {
// 代表一直打印
for (; ; ) {
lock.lock();
while (COUNT % 3 != 0) {
try {
condition.await();
} catch (InterruptedException e) {
}
}
System.out.print("A");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
COUNT++;
condition.signalAll();
lock.unlock();
}
});
Thread t2 = new Thread(() -> {
// 代表一直打印
for (; ; ) {
lock.lock();
while (COUNT % 3 != 1) {
try {
condition.await();
} catch (InterruptedException e) {
}
}
System.out.print("B");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
COUNT++;
condition.signalAll();
lock.unlock();
}
});
Thread t3 = new Thread(() -> {
// 代表一直打印
for (; ; ) {
lock.lock();
while (COUNT % 3 != 2) {
try {
condition.await();
} catch (InterruptedException e) {
}
}
System.out.print("C");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
COUNT++;
condition.signalAll();
lock.unlock();
}
});
t1.start();
t2.start();
t3.start();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!