zoukankan      html  css  js  c++  java
  • 实现Callable接口。带返回值的线程

    callable

    1.任务结束后可以提供一个返回值

    2.其中的call方法可以抛出异常

    3.运行callable可以拿到一个Future对象,Future对象表示异步计算的结果,他提供了检查计算是否完成的方法。

    实现Callable接口

    public class Main implements Callable{
        int i;
        @Override
        public Object call() throws Exception {
            String str=null;
            for (i=0;i<100;i++){
                str=Thread.currentThread().getName()+"--"+i;
                System.out.println(str);
            }
            return str;
        }
    }

    测试

    public class Client {
        public static void main(String[] args) {
            ExecutorService threadPool= Executors.newSingleThreadExecutor();
            Future<String> future=threadPool.submit(new Main());
            System.out.println("----------");
            try {
                System.out.println(future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    线程结束后,future.get()方法会返回结果

  • 相关阅读:
    P3811乘法逆元
    P4549裴蜀定理
    备用代码区
    其他板子整理
    DP
    图论板子整理
    约数
    浅谈假学习假努力
    质数
    P1019 单词接龙
  • 原文地址:https://www.cnblogs.com/neu-student/p/6662035.html
Copyright © 2011-2022 走看看