多线程中 volatile 保证可见性和不保证原子性

多线程中 volatile 保证可见性和不保证原子性,代码说明问题

例1:原子性问题


/**
 * 不能保证原子性
 */
public class VolatileUnsafe2 {
    private volatile long count =0;

    public long getCount() {
        return count;
    }

    public void setCount(long count) {
        this.count = count;
    }

    //count进行累加
    public void incCount(){
        count++;
    }

    //线程
    private static class Count extends Thread{

        private VolatileUnsafe2 simplOper;

        public Count(VolatileUnsafe2 simplOper) {
            this.simplOper = simplOper;
        }

        @Override
        public void run() {
            for(int i=0;i<10000;i++){
                simplOper.incCount();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        VolatileUnsafe2 simplOper = new VolatileUnsafe2();
        //启动两个线程
        Count count1 = new Count(simplOper);
        Count count2 = new Count(simplOper);
        count1.start();
        count2.start();
        Thread.sleep(50);
        System.out.println(simplOper.count);//20000?
    }

}

例2:可见性问题



/**
 * 可见性
 */
public class VolatileVisible {
    public static int count = 1;
    private volatile static boolean ready;//说明,这里将volatile去掉后,将陷入无限循环,是因为子线程看不到ready已经修改

    public static class ThreadT1 implements Runnable {
        @Override
        public void run() {
            System.out.println("run ...");
            while (!ready) ;//无限循环
            System.out.println("end"+count);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new Thread(new ThreadT1()).start();
        Thread.sleep(200);
        count = 20;
        ready = true;
        Thread.sleep(200);
        System.out.println("main end");
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值