通过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();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值