简单了解了一下 Java线程池 ThreadPoolExecutor

参考资料都写在了代码里了:


package com.sondon.mayi.jpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Project : JPool
 * @Package : com.sondon.mayi.jpool
 * @Class : JPoolLearn
 * @Author : 蔡文锋
 * @DateTime:2015年7月24日 下午11:34:34
 * @Blog:http://blog.csdn.net/caiwenfeng_for_23
 * @Description : { 
 * 
 * JAVA自带线程池研究  :
 * 
 * 參考資料:
 * 线程池ThreadPoolExecutor使用简介 :  http://coach.iteye.com/blog/855850
 * Callable接口和Runable接口 :  http://uule.iteye.com/blog/1488270
 * 线程池ThreadPoolExecutor参数设置 :  http://blog.csdn.net/zhouhl_cn/article/details/7392607
 * Java线程池原理以及几种线程池类型介绍 :  http://xtu-xiaoxin.iteye.com/blog/647580 
 *  }
 *
 */
public class JPoolLearn {

	private static int produceTaskSleepTime = 3;
	private static int produceTaskMaxNumber = 20;
	
	public void testThreadPoolExecutor(){
		/*
		 * ThreadPoolExecutor( 
		 * int corePoolSize, //线程池维护线程的最少数量 
		 * int maximumPoolSize, //线程池维护线程的最大数量 
		 * long keepAliveTime, //线程池维护线程所允许的空闲时间
		 * TimeUnit unit, //线程池维护线程所允许的空闲时间的单位 
		 * BlockingQueue<Runnable> workQueue, //线程池所使用的缓冲队列 
		 * RejectedExecutionHandler handler  //线程池对拒绝任务的处理策略 )
		 */
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
				5,
				10, 
				3,
				TimeUnit.SECONDS, 
				new ArrayBlockingQueue<Runnable>(10),
				new ThreadPoolExecutor.DiscardOldestPolicy()
				);

		for (int i = 1; i <= produceTaskMaxNumber; i++) {
			try {
				// 产生一个任务,并将其加入到线程池
				String task = "task---" + i;
				threadPool.execute(new ThreadPoolTask(task));
				System.out.println("activeCount  :"+ threadPool.getActiveCount());
				// 便于观察,等待一段时间
				Thread.sleep(produceTaskSleepTime);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		//查看当前的线程池状况
		while(true){
			try {
				Thread.sleep(3000);
				System.out.println("pool size :"+threadPool.getPoolSize());//线程池中线程数量
				System.out.println("active count :"+threadPool.getActiveCount());//线程池中活动的线程数量
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * @Author 蔡文锋
	 * @Data_Time 2015年7月25日 下午4:06:28
	 * @Description { 测试不同线程池模式 }
	 */
	public void testNewCachedThreadPool(){
		ThreadPoolExecutor threadPool=(ThreadPoolExecutor) Executors.newCachedThreadPool();
//		ThreadPoolExecutor threadPool=(ThreadPoolExecutor) Executors.newFixedThreadPool(100);
//		ThreadPoolExecutor threadPool=(ThreadPoolExecutor) Executors.newScheduledThreadPool(100);
//		ThreadPoolExecutor threadPool=(ThreadPoolExecutor) Executors.newSingleThreadExecutor();
		try {
		for (int i = 0; i < 100; i++) {
			// 产生一个任务,并将其加入到线程池
			String task = "task---" + i;
			threadPool.execute(new ThreadPoolTask(task));
			System.out.println("activeCount  :");
			// 便于观察,等待一段时间
			Thread.sleep(produceTaskSleepTime);
			
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//查看当前的线程池状况
		while(true){
			try {
				Thread.sleep(3000);
				System.out.println("pool size :"+threadPool.getPoolSize());//线程池中线程数量
				System.out.println("active count :"+threadPool.getActiveCount());//线程池中活动的线程数量
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 
	 * @Author 蔡文锋
	 * @Data_Time 2015年7月25日 下午4:06:58
	 * @Description { 测试callable与runable方法的区别 }
	 */
	public void testNewCachedThreadPool_callable(){
		ExecutorService es=Executors.newFixedThreadPool(10);
		try {
			
//			String result=es.submit(new MyCallable<String>()).get();
//			System.out.println("callable  result :"+result);
			
			String result=(String) es.submit(new ThreadPoolTask("")).get();
			System.out.println("runable  result :"+result);
			
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}
	
	
	public static void main(String[] args) {
		new JPoolLearn().testNewCachedThreadPool();
	}
}



/**
 * 线程池执行的任务
 */
class ThreadPoolTask implements Runnable {
	private static int consumeTaskSleepTime = 2000;
	// 保存任务所需要的数据
	private Object threadPoolTaskData;

	ThreadPoolTask(Object tasks) {
		this.threadPoolTaskData = tasks;
	}

	public void run() {
		System.out.println("start .." + threadPoolTaskData);
		try {
			// Sleep 2秒 模拟耗时操作
			Thread.sleep(consumeTaskSleepTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		threadPoolTaskData = null;
	}

	public Object getTask() {
		return this.threadPoolTaskData;
	}
}

/**
 * 
 * @Project : JPool
 * @Package : com.sondon.mayi.jpool
 * @Class : MyCallable
 * @param <T>
 */
class MyCallable<T> implements Callable<T>{
	
	@Override
	public T call() throws Exception {
		 System.out.println("开始执行Callable");  
		 return (T) "测试callable接口";
	    }  
}



你可能感兴趣的:(线程池)