java i++ 并非原子操作的解决方法——用AtomicInteger

public class Test1 {
	private static  int a = 0;
	public static void main(String[] args) throws InterruptedException{
		System.err.println("LOL");
		int n=500000;
		while(n-->0){
			startAdd();
		}
		Thread.sleep(2000);
		System.err.println(a);
	}
	public static void startAdd(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				a++;
			}
		}).start();
	}
}


运行了5次结果

499980

499984

499982

499973

499989


而如果用AtomicInteger

public class Test2 {
	private static  AtomicInteger a = new AtomicInteger(0);
	public static void main(String[] args) throws InterruptedException{
		System.err.println("LOL");
		int n=500000;
		while(n-->0){
			startAdd();
		}
		Thread.sleep(2000);
		System.err.println(a);
	}
	public static void startAdd(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				a.getAndIncrement();
			}
		}).start();
	}
}
运行5次结果

500000

500000

500000

500000

还是500000

懂了吧


你可能感兴趣的:(java)