http://haininghacker-foxmail-com.iteye.com/blog/1401346    这个偏重介绍

http://hittyt.iteye.com/blog/1130990    这个比较偏重它的实现原理

 

引出

public class All {
	public static int i = 0;
	
	private class MyThread extends Thread{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			int j = 10;
			while(0!=j--){
				i++;
			}
		}
	}
	
	public static void main(String[] args) {
		All all = new All();
		all.new MyThread().start();
		all.new MyThread().start();
		all.new MyThread().start();
		all.new MyThread().start();
		all.new MyThread().start();
		all.new MyThread().start();
		System.out.println(All.i);
	}
}

  今天编程实验累加器,没有同步的情况下,数据有时会不准,这是很可怕的;网上找到了这个AtomicInteger非阻塞同步;

  在看它的原理时,有点晕,主要是compareAndSet这个方法;volatile关键字的使用方法可以理解。

  compareAndSet到底是什么呢?我寻到了几篇博文:

  http://blog.csdn.net/aesop_wubo/article/details/7537278

  http://zeige.iteye.com/blog/1182571

  主要讲的是java底层的unsafe实现,说到,更新是比较原值,原值不同就不更新现在的值

  public final int incrementAndGet() {  
       for (;;) {  
           //这里可以拿到value的最新值  
           int current = get();  
           int next = current + 1;  
           if (compareAndSet(current, next))  
               return next;  
       }  
   }  

可是这样,如果出现错误,怎么跳出循环呢?还是没有看懂,希望有大大能指引一下;