• JAVA线程池中的Callable和Future


    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();
            }
        }
    
    }
  • 相关阅读:
    前Citrix技术总监:虚拟化将解决云计算安全问题 狼人:
    悲剧:金山毒霸官网被黑客攻破 狼人:
    接口程序设计Windows CE嵌入式系统程序开发
    参数返回Oracle 常用函数:nvl/nullif/case when/wm_concat/replace
    数据恢复[Oracle] Flashback闪回机制
    重复字段Oracle删除重复行
    进程函数一步步理解Linux之信号
    读取数据事务
    菜单函数Android学习整理菜单Menu
    参数实现Oracle SQL中实现indexOf和lastIndexOf功能
  • 原文地址:https://www.cnblogs.com/duwenlei/p/5105628.html
Copyright © 2020-2023  润新知