美文网首页
多线程(10) — Callable与Future

多线程(10) — Callable与Future

作者: 烧杰 | 来源:发表于2018-04-17 22:25 被阅读0次

    作用:获得线程执行完的结果

    package ThreadPractice;
    
    import java.util.concurrent.*;
    
    /**
     * Created by qiaorenjie on 2018/3/28.
     */
    public class CallableAndFuture {
    
        public static void main(String[] args) {
             // 1.提交一条线程
             ExecutorService threadPool = Executors.newSingleThreadExecutor();
             Future<String> future =
             threadPool.submit(
                     new Callable<String>() {  // 注意Callable与Future类型必须一致用泛型
                         @Override    // 注意new的是callable
                         public String call() throws Exception { // 不再是runnable中的run而是callable中的call
                             Thread.sleep(2000);
                             return "Hello";
                         }
                     }
             );
            System.out.println("等待结果");
            try {
                System.out.println("拿到结果:" + future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
    
            //2.提交一组线程
            ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
            CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);
            for (int i = 1; i <= 10; i++) {
                final int seq = i;
                completionService.submit(new Callable<Integer>() {
                    @Override
                    public Integer call() throws Exception {
                        Thread.sleep(new Random().nextInt(5000));
                        return seq;
                    }
                });
            }
            for (int i = 0; i < 10; i++) {
                try {
                    System.out.println(completionService.take().get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
    
        }
    }
    
    =====console======
    等待结果
    拿到结果:Hello
    
    

    由此,可以看出Callable接口方法下的call用于写回调结果,new的callable必须要重写call()方法,而call()方法是需要return返回的,在ruturn中写需要回调的信息,再通过Future的get()方法获取到回调的结果数据

    相关文章

      网友评论

          本文标题:多线程(10) — Callable与Future

          本文链接:https://www.haomeiwen.com/subject/bfducftx.html