AtomicInteger原子类

public class ThreadPool {

	private static ExecutorService threadPool = null;
	private static int corePoolSize=10;//始终有corePoolSize个线程在执行(waiting状态)
	private static int maximumPoolSize=100;//taskthread数量超过maximumPoolSize,可能会有如干个辅助线程,状态为TIMED_WAITING
	private static long keepAliveTime=15;//线程池活跃时间,是毫秒,秒还是分取决于TimeUnit*
	private static TimeUnit unit=TimeUnit.SECONDS;
	
	public static ExecutorService getThreadPool(){
		if(threadPool==null){
			BlockingQueue<Runnable> workQueue=new ArrayBlockingQueue<Runnable>(maximumPoolSize, false);//如果为 false,则访问顺序是不确定的
			CallerRunsPolicy handler=new ThreadPoolExecutor.CallerRunsPolicy();
			threadPool=new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
		}
		return threadPool;
	}
	
}
public class TaskCallable implements Callable<Integer> {

	private AtomicInteger ai;
	
	
	public TaskCallable(AtomicInteger ai) {
		this.ai = ai;
	}
	
	public Integer call() throws Exception {
		int a = ai.incrementAndGet();
		System.out.println(Thread.currentThread().getName()+"==="+a);
//		System.out.println(a+"---");
		return a;
	}
}
public static void main(String[] args) {
		AtomicInteger ai = new AtomicInteger(0);
		ExecutorService threadPool = ThreadPool.getThreadPool();
		for (int i = 0; i < 10; i++) {
//			TaskCallable tc = new TaskCallable(ai);
			TaskCallable tc = new TaskCallable(ai);
			
			Future<Integer> future = threadPool.submit(tc);
			try {
				System.out.println(future.get());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}

print:

pool-1-thread-1===1
1
pool-1-thread-2===2
2
pool-1-thread-3===3
3
pool-1-thread-4===4
4
pool-1-thread-5===5
5
pool-1-thread-6===6
6
pool-1-thread-7===7
7
pool-1-thread-8===8
8
pool-1-thread-9===9
9
pool-1-thread-10===10
10

猜你喜欢

转载自itace.iteye.com/blog/2278876