首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

newFixedThreadPool与Callable组合用法

2013-12-28 
newFixedThreadPool与Callable结合用法package com.sohu.testimport java.util.ArrayListimport java.ut

newFixedThreadPool与Callable结合用法

package com.sohu.test;import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.FutureTask;/** * @author qiaowang * @date 2013-12-26 上午10:39:01 */public class TestThreadDemo {    private ExecutorService exec;    private int cpuNum;    private List<Future<Long>> tasks = new ArrayList<Future<Long>>();        class SumCalculator implements Callable<Long> {          private int[] numbers;          private int start;          private int end;            public SumCalculator(final int[] numbers, int start, int end) {              this.numbers = numbers;              this.start = start;              this.end = end;          }            public Long call() throws Exception {              Long sum = 0l;              for (int i = start; i < end; i++) {                  sum += numbers[i];              }              return sum;          }      }           public TestThreadDemo() {        cpuNum = Runtime.getRuntime().availableProcessors();        exec = Executors.newFixedThreadPool(cpuNum);    }        public Long sum(final int[] numbers) {          // 根据CPU核心个数拆分任务,创建FutureTask并提交到Executor          System.out.println(cpuNum);        for (int i = 0; i < cpuNum; i++) {              int increment = numbers.length / cpuNum + 1;              int start = increment * i;              int end = increment * i + increment;              if (end > numbers.length)                  end = numbers.length;              SumCalculator subCalc = new SumCalculator(numbers, start, end);              FutureTask<Long> task = new FutureTask<Long>(subCalc);              tasks.add(task);              if (!exec.isShutdown()) {                  exec.submit(task);              }          }          return getResult();      }        public Long getResult() {        Long result = 0l;        for(Future<Long> task : tasks){            try {                Long subSum = task.get();                result +=subSum;            } catch (Exception e) {                e.printStackTrace();            }        }        return result;    }        public void close(){        exec.shutdown();    }        public static void main(String args[]){        int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 10, 11 ,12};          TestThreadDemo calc = new TestThreadDemo();          Long sum = calc.sum(numbers);          System.out.println(sum);          calc.close();     }}


参见
http://www.iteye.com/topic/366591

Executors类,提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口。
public static ExecutorService newFixedThreadPool(int nThreads)
创建固定数目线程的线程池。
public static ExecutorService newCachedThreadPool()
创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
public static ExecutorService newSingleThreadExecutor()
创建一个单线程化的Executor。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。

热点排行