AtomicInteger原子型整数

1、先用普通int类型变量举例

public class T_int {
        static int i = 0;
	public static void main(String[] args) {
		
		new Thread(new Add()).start();
		new Thread(new Add()).start();
		
		System.out.println("i="+i);		
	}
}

class Add implements Runnable{

	@Override
	public void run() {

		for (int i = 0; i < 1000; i++) {
			T_int.i++;
		}
	}	
}

 通过测试发现大部分的结果i都为0,只有少量时i等于了不是很大的数字,原因很简单,就是因为线程抢占,在new的两个线程还没有执行完的时候(也有可能就让两个线程还没有执行),打印语句就已经打印完毕。于是就有了以下改进方法:

2、加入CountDownLatch,原本的本意是希望可以通过让两个线程共同完成循环结束后再释放两个线程进行打印。

import java.util.concurrent.CountDownLatch;

public class T_int {
	
	static int i = 0;
	
	public static void main(String[] args) throws InterruptedException {
		
		CountDownLatch cdl = new CountDownLatch(2);
		
		new Thread(new Add(cdl)).start();
		new Thread(new Add(cdl)).start();
		
		cdl.await();
		
		System.out.println("i="+i);
	}
}

class Add implements Runnable{

	private CountDownLatch cdl;
	
	public Add(CountDownLatch cdl) {
		super();
		this.cdl = cdl;
	}

	@Override
	public void run() {

		for (int i = 0; i < 1000; i++) {
			T_int.i ++ ;
		}
		
		cdl.countDown();
	}

最后的控制台的结果是有时等于2000,有时时一些比较大的数,这是因为两个线程各自在内存独享一个栈,也就意味着各自线程拿到了一个i,进行自己的i++操作,然后再赋值给原来的i,每个线程操作的不是同一个i,这样就会导致最终结果不一定为2000,

3、为了避免这种情况,就可以采用给int的变量i加锁的方式,每次再给i进行线程运算的时候加锁,操作完毕后再释放,于是有一个新类可以解决这种情况AtomicInteger原子型整数。

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class t_AtomicInteger {

	//原子型锁,底层采用了锁机制
	static AtomicInteger ai = new AtomicInteger(0);
	
	public static void main(String[] args) throws InterruptedException {		
		
		CountDownLatch cdl = new CountDownLatch(2);
	
		new Thread(new Add(cdl)).start();
		new Thread(new Add(cdl)).start();
		
		cdl.await();
		
		System.out.println(ai);
	}
}

class Add implements Runnable{

	private CountDownLatch cdl;
	
	public Add(CountDownLatch cdl) {
		super();
		this.cdl = cdl;
	}

	@Override
	public void run() {
		
		for(int i = 0;i < 1000; i++){
			//用自身的方法进行自增
			t_AtomicInteger.ai.incrementAndGet();
		}
		cdl.countDown();
	}	
}

这样每次操作完毕之后的结果就都是2000,因为给i加锁后,每个线程进行自增的都是同一个i,最终结果也就会一样。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值