java线程池的应用

package com.test;

import java.util.concurrent.Callable;

public class TestThread implements Callable<Object>{

    @Override
    public Object call() throws Exception {
        System.out.println(123);
        return 456;
    }

}
package com.test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestPool {

    public void handleThreadPool(){
        int threadCount = 5;
        int poolSize = 3;
        TestThread[] tt = new TestThread[threadCount];
        ExecutorService service = Executors.newFixedThreadPool(poolSize);
        Collection<TestThread> c = new ArrayList<TestThread>();
        for (int i = 0; i < threadCount; i++) {
            tt[i] = new TestThread();
            c.add(tt[i]);
        }
        try {
            List<Future<Object>> results = service.invokeAll(c);
            service.shutdown();
            for (Future<Object> future : results) {
                 System.out.println(future.get().toString());
            }
        } catch (InterruptedException e) {            
            e.printStackTrace();
        } catch (ExecutionException e) {    
            e.printStackTrace();
        }        
    }
    
    public static void main(String[] args){
        TestPool tp = new TestPool();
        tp.handleThreadPool();
    }

}

 

posted on 2013-09-13 11:43  张飞_  阅读(284)  评论(0编辑  收藏  举报

导航