1 package com.noway.test; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 import java.util.concurrent.Callable; 6 import java.util.concurrent.ExecutionException; 7 import java.util.concurrent.FutureTask; 8 import java.util.concurrent.atomic.AtomicInteger; 9 10 /** 11 * AtomicInteger和Integer区别 12 * AtomicInteger可保证多线程中保持原子操作,适用于在多线程中的计算 13 * @author Noway 14 */ 15 public class TestAtomicInteger { 16 17 static Integer result = 0; 18 19 static AtomicInteger ai = new AtomicInteger(); 20 21 public static void main(String[] args) throws InterruptedException, ExecutionException { 22 List<FutureTask<Integer>> ftList = new ArrayList<FutureTask<Integer>>(); 23 for (int i = 0; i < 10000; i++) { 24 FutureTask<Integer> ft = new FutureTask<Integer>(new Callable<Integer>() { 25 @Override 26 public Integer call() throws Exception { 27 result+= 1; 28 return ai.incrementAndGet(); 29 } 30 }); 31 new Thread(ft).start(); 32 ftList.add(ft); 33 } 34 for (int i = 0; i < ftList.size(); i++) { 35 ftList.get(i).get();//保证所有的线程执行完成 36 } 37 System.out.println("result====="+result); 38 System.out.println("ai===="+ai.get()); 39 } 40 41 }