面试题 -- 两个线程交替运行

业务场景:应付面试。

实战价值:代码过于复杂难以维护,实际生产不可能手搓线程,执行这种操作。

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Mr.css
 * @version 2022-08-03 16:36
 */
public class AlternatePrint {

    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition thread1Condition = lock.newCondition();
    private static final Condition thread2Condition = lock.newCondition();
	// isThread1Turn 用于指示当前是否轮到 Thread1 打印。
    private static boolean isThread1Turn = true;

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Task("Thread1", 1, 10), "Thread1");
        Thread thread2 = new Thread(new Task("Thread2", 2, 10), "Thread2");

        thread1.start();
        thread2.start();
    }

    static class Task implements Runnable {
        private final String name;
        private final int start;
        private final int end;

        public Task(String name, int start, int end) {
            this.name = name;
            this.start = start;
            this.end = end;
        }

        @Override
        public void run() {
            for (int i = start; i <= end; i++) {
                lock.lock();
                try {
					// 这一行代码有点乱,代码含义就是:轮到一个线程执行时,将另一个线程暂停
                    while ((isThread1Turn && !name.equals("Thread1")) || (!isThread1Turn && !name.equals("Thread2"))) {
                        if (name.equals("Thread1")) {
                            thread1Condition.await();
                        } else {
                            thread2Condition.await();
                        }
                    }

                    System.out.println(name + ": " + i);

                    if (name.equals("Thread1")) {
                        isThread1Turn = false;
                        thread2Condition.signal();
                    } else {
                        isThread1Turn = true;
                        thread1Condition.signal();
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}

posted on   疯狂的妞妞  阅读(146)  评论(0编辑  收藏  举报

(评论功能已被禁用)
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示