Java多线程开发九——线程池2

JDK1.5还提供了Callable<T>和Future<T>接口,用于线程池执行任务并获取返回值。下面给出一个简单的示例代码。

1. 实现一个任务

 

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;
    }

}

 2.使用线程池执行任务并获取返回值

 

public class ThreadPoolSample ...{

    
float[][] scores = ......8786909176 }...5634667865 },
            
...9997958789 }...7776757885 },
            
...8856787876 } }
;

    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) ...{
        ThreadPoolSample sample 
= new ThreadPoolSample();
        
try ...{
            sample.count();
        }
 catch (InterruptedException e) ...{

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

            e.printStackTrace();
        }

    }


}

 

附:自己实现一个线程池

Tomcat的源代码中实现了一个线程池,有兴趣可以看一下。在connectors的util下面。具体目录:org\apache\tomcat\util\threads

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值