线程池的用法

一、不带返回值的线程池方法

 

如果想让他带返回值,需要做一些特殊处理。主要思想如下:

 

 

 

二、带返回值的方法:(http://softstone.javaeye.com/blog/172903

 

 

package cn.edu.xjtu.nhpcc.jenva.threadpool;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class TestCall2 {

   float[][] scores = { { 87, 86, 90, 91, 76 }, { 56, 34, 66, 78, 65 },
          { 99, 97, 95, 87, 89 }, { 77, 76, 75, 78, 85 },
          { 88, 56, 78, 78, 76 } };

  Future<Float>[] result = new Future[5];

  public void count() throws InterruptedException, ExecutionException {
      //创建线程池
      ExecutorService pool = Executors.newFixedThreadPool(5);
      for (int i = 0; i < scores.length; i++) {
          //提交任务,获取结果
          result[i] = pool.submit(new Caller(scores[i]));
      }
      for (int i = 0; i < result.length; i++){
          System.out.println(result[i].get());
      }
      //关闭线程池
      pool.shutdown();
  }

  public static void main(String[] args) {
   TestCall2 sample = new TestCall2();
      try{
          sample.count();
      } catch (InterruptedException e) {

          e.printStackTrace();
      } catch (ExecutionException e) {

          e.printStackTrace();
      }
  }
 
  public class Caller implements Callable<Float> {
     private float[] score;

     public Caller(float[] score){
         this.score = score;
     }
     /** *//**
      * 计算平均分
      */
     public Float call() throws Exception {
         float sum = 0;
         for (int i=0;i<score.length;i++){
             sum+=score[i];
         }
         return sum/score.length;
     }
 }
 
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值