【Java】多线程:N个线程交替打印M个数的几种方法(无锁)

1. 加锁互斥

public class Test02LockAndWait {
    static int N = 4;
    static int M = 50;
    static Object o = new Object();
    static volatile AtomicInteger count = new AtomicInteger(0);

    static class MyThread extends Thread {
        int id;

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

        @Override
        public void run() {
            while (count.get() < M) {
                synchronized (o) {
                    if (count.get() < M && count.get() % N == id) {
                        // 类似双检锁
                        System.out.println(Thread.currentThread().getName() + "-" + count.incrementAndGet());
                    }
                }
            }
        }
    }

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

2. wait + notifyAll 中断唤醒(还是有锁)

wait跟notifyAll的监视器还是有竞争风险,依然需要加锁(不如直接加锁互斥)

public class Test02LockAndWait {
    static int N = 4;
    static int M = 50;
    static Object o = new Object();
    static volatile AtomicInteger count = new AtomicInteger(0);

    static class MyThread extends Thread {
        int id;

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

        @Override
        public void run() {
            while (count.get() < M) {
                synchronized (o) {
                    if (count.get() < M && count.get() % N != id) {
                        try {
                            o.wait();
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (count.get() < M && count.get() % N == id) {
                        System.out.println(Thread.currentThread().getName() + "-" + count.incrementAndGet());
                        try {
                            o.notifyAll();
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

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

3. 忙等待

参考N个线程在不加锁的情况下交替打印M个数字 ,个人做了点优化,不需要额外的now来计数。

public class Test03CAS {
    static final int N = 4;
    static final int M= 50;
    static AtomicInteger count = new AtomicInteger(0);

    static class MyThread extends Thread{
        int id;
        public MyThread(int id){
            this.id = id;
        }

        @Override
        public void run() {
            while (count.get() < M){
                if (count.get() % N != id) {
                    continue;
                } else{
                    try {
                        sleep(100); // 保证打印顺序
                        System.out.println(Thread.currentThread().getName() + "-" + count.incrementAndGet());
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }

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

4. LockSupport定向唤醒线程

需要一个Thread[]数组额外纯一下所有的线程对象

public class Test04LockSupport {
    // N个线程打印M个数
    private static final int N = 4;
    private static final int M = 50;
    private static volatile AtomicInteger count = new AtomicInteger(0);
    private static final Thread[] threads = new Thread[N];

    public static void main(String[] args) {
        class MyThread extends Thread {
            int id;

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

            @Override
            public void run() {
                while (count.get() < M){
                    if (count.get() % N != id){
                        LockSupport.park();
                    }else{
                        System.out.println(Thread.currentThread().getName() + "-" + count.incrementAndGet());
                        LockSupport.unpark(threads[(id+1) % N]);
                    }
                }
                LockSupport.unpark(threads[(id+1) % N]);
            }
        }

        for (int i = 0; i < N; i++){
            threads[i] = new MyThread(i);
            threads[i].start();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值