java并发系列之java.util.concurrent.atomic包下面的原子类

 以AtomicInteger 类为例实现计数

package thread;

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicDemo {

	private AtomicInteger atomicInteger = new AtomicInteger(0);
	
	public AtomicInteger getAtomicInteger() {
		return atomicInteger;
	}

	public void setAtomicInteger(AtomicInteger atomicInteger) {
		this.atomicInteger = atomicInteger;
	}

	public static void main(String[] args) throws InterruptedException {
		final AtomicDemo atomicDemo = new AtomicDemo();
		
		for (int i = 0; i < 100000; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					//getAndIncrement方法,先获取再加1,具有原子性
					atomicDemo.getAtomicInteger().getAndIncrement();
				}
			}).start();
		}
		
		Thread.sleep(10000);
		//10秒不一定就出结果,但结果一定是100000
		System.err.println(atomicDemo.getAtomicInteger().get());
		
	}
	
	
	
}
发布了89 篇原创文章 · 获赞 67 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/xl_1803/article/details/99981354