Java 两个线程按顺序交叉打印1-100数字

方案一使用锁:

通过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();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值