线程池使用简单示例

 1 private static ExecutorService executor = Executors.newFixedThreadPool(4);
 2 public void dispatch() {
 3         while (true) {
 4             List<Callable<String>> tasks = new ArrayList<Callable<String>>();
 5             List<Member> memberList = taskTodo(); //当前需要处理的任务集
 6             for (final Member each : memberList) {
 7                 tasks.add(new Callable<String>() {
 8                     @Override
 9                     public String call() {
10                         todoEachTask(each); //处理每个任务
11                         return "ok";
12                     }
13                 });
14             }
15             try {
16                 executor.invokeAll(tasks, 480, TimeUnit.SECONDS); //如果8分钟还未执行完,则超时重新再来
17             }catch (Exception e) {
18             }
19             try {
20                 Thread.sleep(1000); //休眠1秒后继续处理任务
21             } catch (InterruptedException e) {
22             }
23         }
24     }

注意: private static  ExecutorService executor = Executors.newCachedThreadPool(); 

newCachedThreadPool最大线程数为整型的最大值,每提交一个任务,如果没有线程处理,那就产生一个新的线程。当我们for循环提交任务时,开辟了上百个线程,应用程序马上崩溃

posted @ 2018-03-01 14:41  秋水秋色  阅读(137)  评论(0编辑  收藏  举报