count++不是原子性操作测试

package com.ssy.base;


import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;


public class CountJIAJIATest {


    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
        for(int i=0;i<1000;i++){// 执行1000次,其中会有几次不符合预期
            new CountTest().run();
        }
    }
}


/**
 * @Author saintshi
 * @Date 2016年2月1日 下午4:46:47
 * 注:其中CyclicBarrier的作用是等到所有线程都执行完成之后再执行下一步
 * 在这里的作用是,主线程等待子线程执行完在执行下一步(count.get())
 */
class CountTest{
    final Count count = new Count();
    final int _num_thread = 100;
    final int _num_count = 1000;
    final CyclicBarrier cb = new CyclicBarrier(_num_thread+1);
    public void run(){
        try {
            for(int i=0;i<_num_thread;i++){
                Thread t = new Thread(){
                    public void run() {
                        try {
                            for(int j=0;j<_num_count;j++){
                                count.add();
                            }
                            cb.await();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    };
                };
                t.setDaemon(false);
                t.start();
            }
            cb.await();
            int result = count.get();
            if(result!=_num_thread*_num_count){
                System.out.println(result);// 如果不符合预期(count++原子执行)就会打印
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class Count{
    private int count;
    public void add(){
//        synchronized (this) {// 如果不加上会出现与不符合预期的结果
            count++;
//        }
    }
    public int get(){
        return count;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值