实现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()方法会返回结果

原文地址:https://www.cnblogs.com/neu-student/p/6662035.html