Quelle est la raison pour laquelle nous devons utiliser un pool de threads ?
Personnellement, je pense que la raison principale est la suivante : il y a beaucoup de tâches qui doivent être traitées en peu de temps.
Avantages de l'utilisation d'un pool de threads :
1. Réduisez le temps passé à créer et à détruire les threads et la surcharge des ressources système
2. Si vous n'utilisez pas de pool de threads, le système peut créer un grand nombre de threads et consommer toute la mémoire système
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; 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接口"; } }