多线程加法如何保证

多线程加法如何保证

我们先来看一下多线程直接相加的例子

public class CasDemo {
	public static int count = 0;	
	public static void main(String[] args) {
		//long startTime = System.currentTimeMillis();
		//开启两个线程
		for(int i = 0;i<2;i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(10);
					}catch(InterruptedException e) {
						e.printStackTrace();
					}
					//每个线程当中让count值自增100次
					for(int j = 0;j<10000000;j++) {
						//synchronized (CasDemo.class) {
							count++;
						//}
					}
				}}).start();
		}
		try {
			Thread.sleep(2000);
		}catch(InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("count="+count);
		//long endTime = System.currentTimeMillis();
		//System.out.println(endTime-startTime);
	}
}

输出结果为count=10731025可以看到这是一个错误的结果,那么如果保证多线程相加的安全呢。

采用java同步关键字synchronized

我们在循环里面添加synchronized就可以了(也就是把上面注释的代码放开)。但是,这样子加同步锁,比较慢。怎么办呢,
这里还有别的方法

采用AtomicInteger类

package cc.flybb;

import java.util.concurrent.atomic.AtomicInteger;

public class CasDemo2 {

	public static AtomicInteger count = new AtomicInteger(0);
	
	public static void main(String[] args) {
		//long startTime = System.currentTimeMillis();
		//开启两个线程
		for(int i = 0;i<2;i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(10);
					}catch(InterruptedException e) {
						e.printStackTrace();
					}
					//每个线程当中让count值自增100次
					for(int j = 0;j<100000;j++) {
						//synchronized (CasDemo2.class) {
							count.incrementAndGet();
						//}
					}
				}}).start();
		}
		try {
			Thread.sleep(2000);
		}catch(InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("count="+count);
		//long endTime = System.currentTimeMillis();
		//System.out.println(endTime-startTime);
	}

}

输出结果是一样的count=200000

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值