zoukankan      html  css  js  c++  java
  • NO.10 Callable与Future的应用

    代码:

    package thread;
    
    import java.util.Random;
    import java.util.concurrent.Callable;
    import java.util.concurrent.CompletionService;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorCompletionService;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class CallableAndFature {
    
        /**
         * @param args
         * @throws ExecutionException 
         * @throws InterruptedException 
         */
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            
            /**
             * code 1
             */
            ExecutorService  pool = Executors.newSingleThreadExecutor();
            Future<String> future =
            pool.submit(new Callable<String>() {
    
                @Override
                public String call() throws Exception {
                    Thread.sleep(2000);
                    return "hello";
                }
            });
            System.out.println(future.get());
            pool.shutdown();
            
            /**
             * code 2
             */
            ExecutorService  pool2 = Executors.newFixedThreadPool(5);
            
            CompletionService<Integer> server = new ExecutorCompletionService<Integer>(pool2);
            for(int i = 1; i <= 10; i ++) {
                final int seq = i;
                server.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(server.take().get());
            }
            
            
        }
    
    }
     
  • 相关阅读:
    精简shell基础
    Centos7.4下安装Jumpserver 1.0.0(支持windows组件)
    二.Flask 学习模板
    一、Flask路由介绍
    web爬虫,BeautifulSoup
    web爬虫,requests请求
    django之Form组件补充
    中间件和Django缓存
    django之Form组件
    django from表单验证
  • 原文地址:https://www.cnblogs.com/royi123/p/3123126.html
Copyright © 2011-2022 走看看