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());
            }
            
            
        }
    
    }
     
  • 相关阅读:
    editplus 快捷键
    python 堆栈
    python 矩阵转置
    python 单向链表
    python 读空的json文件
    c++ 结构体
    手把手教你如何利用Meterpreter渗透Windows系统
    vuejs npm chromedriver 报错
    强大的开源网络侦查工具:IVRE
    在vue 中使用Stylus
  • 原文地址:https://www.cnblogs.com/royi123/p/3123126.html
Copyright © 2011-2022 走看看