码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA线程池中的Callable和Future

时间:2016-01-06 15:29:55      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Callable Future  completionService test
 * 
 * Future取得结果类型和Callable返回的结果
 * 
 * Callable需要ExecutorService使用submit方式提交
 * 
 * CompletionService 用于提交一组Callable,其中take方法返回已经完成的Callable任务
 * 
 * @author duwenlei
 *
 */
public class CallableFutureTest {

    private static void testCallable() throws Exception {
        ExecutorService service = Executors.newSingleThreadExecutor();
        Future<String> future = service.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(5000);    //停止5秒返回
                return "hello";
            }
        });
        System.out.println("等待结果");
        System.out.println("取得结果:"+future.get());
        //System.out.println("取得结果:"+future.get(1, TimeUnit.SECONDS));
        service.shutdown();
    }
    
    private static void testCompletionService() throws Exception{
        ExecutorService executor = Executors.newFixedThreadPool(3);
        CompletionService<Integer> service = new ExecutorCompletionService<Integer>(executor);    //需要一个线程池
        for (int i = 1; i <= 10; i++) {
            final int seq = i;
            service.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    Thread.sleep(new Random().nextInt(5000));    //休息时间,不确定
                    return seq;
                }
            });
        }
        for (int i = 1; i <= 10; i++) {
            System.out.println(service.take().get());
        }
        executor.shutdown();
    }
    
    public static void main(String[] args) {
        try {
            testCallable();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            testCompletionService();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

JAVA线程池中的Callable和Future

标签:

原文地址:http://www.cnblogs.com/duwenlei/p/5105628.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!