栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

通过volatile的可见性使线程按顺序执行(cas)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过volatile的可见性使线程按顺序执行(cas)

volatile static int flag=0;
    //#region
    public static void main(String[] args) throws Exception {
        int num=100;
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            new Thread(()->{
                while(true){
                    if(flag== finalI){
                        System.out.println(Thread.currentThread().getName()+": "+finalI);
                        flag++;
                        break;
                    }
                }
            },"t"+i).start();
        }
    }
    //#endregion
}

直接通过循环不能按顺序是因为线程按顺序启动并不代表线程会按顺序执行,t1.start();t2.start;无法保证t1一定比t2先执行run方法。因此要通过一个线程共享volatile变量保证顺序

for (int i = 0; i < 100; i++) {
            int finalI = i;
            new Thread(()->{
                        System.out.println(Thread.currentThread().getName()+": "+ finalI);
            },"t"+i).start();
        }
通过countdownlatch,原理同volatile,存在一个线程共享变量
 static CountDownLatch cdl =  new CountDownLatch(100);
    //#region
    public static void main(String[] args) throws Exception {
        int num=100;
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            new Thread(()->{
                while(true){
                    if(cdl.getCount()== 100-finalI){
                        System.out.println(Thread.currentThread().getName()+": "+finalI);
                        cdl.countDown();
                        break;
                    }
                }
            },"t"+i).start();
        }
    }
semaphore配合原子类控制输出数顺序但不能控制线程顺序

semaphore(1) 类似锁机制。

static AtomicInteger num = new AtomicInteger(100);
    //#region
    public static void main(String[] args) throws Exception {
        Semaphore se = new Semaphore(1);
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            new Thread(()->{
                boolean isAcquire = false;
                try {
                    se.acquire();
                    isAcquire = true;
                    System.out.println(Thread.currentThread().getName()+": "+num.getAndIncrement());

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    if(isAcquire){
                    se.release();}
                }

            },"t"+i).start();
        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/727752.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号