通常使用Executors工厂类实现线程池 * newFixedThreadPool();
//斐波那契数列,模拟线程处理任务的时延 public static int fbc(int n){ if(n == 0) return 0; if(n == 1) return 1; return fbc(n-1) + fbc(n-2); } //创建线程数目确定的线程池,corePoolSize = maximumPoolSize , workQuene是LinkedBlockingQuene无界限 public static void testFixedThreadPool() throws InterruptedException, ExecutionException{ ExecutorService executorService = Executors.newFixedThreadPool(3); for(int i=0; i<9; i++){ Future<Integer> future = executorService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { // TODO Auto-generated method stub System.out.println("执行线程:"+Thread.currentThread().getName()); return fbc(0); } }); System.out.println("第"+i+"次结果:"+" "+future.get()); } } newCachedThreadPool(); //创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。 public static void testCachedThreadPool() throws InterruptedException, ExecutionException{ ExecutorService executorService = Executors.newCachedThreadPool(); for(int i=0; i<9; i++){ Future<Integer> future = executorService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { // TODO Auto-generated method stub System.out.println("执行线程:"+Thread.currentThread().getName()); return fbc(0); } }); //System.out.println("第"+i+"次结果:"+" "+future.get()); } } newScheduledThreadPool(); //创建周期执行的线程池,第一个参数是线程任务,第二个参数延迟n,第三个参数是每隔m执行一次,第四个是时间单位。 public static void testScheduledThreadPool(){ ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3); executorService.scheduleAtFixedRate(new Runnable() { public void run() { System.out.println("第1次:"+fbc(20) + "--->"+Thread.currentThread().getName()); } },1,3,TimeUnit.SECONDS); executorService.scheduleAtFixedRate(new Runnable() { public void run() { System.out.println("第2次:"+fbc(20) + "--->"+Thread.currentThread().getName()); } },1,3,TimeUnit.SECONDS); } newSingleExecutor(); //创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。 public static void testSingleExecutor() throws InterruptedException, ExecutionException{ ExecutorService executorService = Executors.newSingleThreadExecutor(); for(int i=0; i<9; i++){ Future<Integer> future = executorService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { // TODO Auto-generated method stub System.out.println("执行线程:"+Thread.currentThread().getName()); return fbc(20); } }); System.out.println("第"+i+"次结果:"+" "+future.get()); } }一般需要根据任务的类型来配置线程池大小:
如果是CPU密集型任务,就需要尽量压榨CPU,参考值可以设为 NCPU+1。
如果是IO密集型任务,参考值可以设置为2*NCPU,很多线程在等IO资源没有工作。