N个线程在不加锁的情况下交替打印M个数字

 思路是自己实现一个 Thread,名为 MyThread,成员变量有 id,这是每一个线程都有的 id,静态变量 now 是当前该哪个线程打印数字了,也是一个 ID。

并且使用 AtomicInteger 保证数字的并发安全,只需要将每一个线程的任务设置为如下所示:

while (atomicInteger.get() < M) {
    if (now != id) {
        continue;
    } else {
        System.out.println(id + " - " + atomicInteger.getAndIncrement());
        now = (now + 1) % N;
    }
}

当 now != id 时,证明现在轮不到此线程打印,那么让它空轮询。 由于每一个线程都需要知道 now 的最新值,所以要将其设置为  volatile

public class Main {
    /**
     * 最大线程数
     */
    private static final int N = 10;
    /**
     * 打印的最大值
     */
    private static final int M = 100;

    static class MyThread extends Thread {
        /**
         * 当前线程的id,不变
         */
        private int id;
        /**
         * 现在该哪个线程打印了,递增
         */
        private static volatile int now;

        private static final AtomicInteger NUM = new AtomicInteger(0);


        public MyThread(int id) {
            this.id = id;
            this.setName("线程" + id);
        }

        @Override
        public void run() {
            while (NUM.get() < M) {
                if (id != now) {
                    continue;
                } else {
                    System.out.println(Thread.currentThread().getName() + " - " + NUM.getAndIncrement());
                    now = (now + 1) % N;
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < N; i++) {
            MyThread myThread = new MyThread(i);
            myThread.join();
            myThread.start();
        }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值