并发库:有返回结果的多线程

要想实现多线程可以返回一个结果,需要涉及到ExecutorService、Callable和Future这三个类。

如果是要执行某个线程任务而不用返回任何结果,就使用execute方法来执行Runnable线程任务。

但是如果想要返回一个结果,就需要用到ExecutorService接口的submit方法。

该方法可以传递一个Callable<V>接口(可以使用匿名内部类),覆盖重写其中的call方法

执行submit方法之后会返回一个Future对象,存放了返回的数据,使用Future类中的get方法就能拿到返回的数据。

示例如下:

public static void main(String[] args) throws ExecutionException, InterruptedException {
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future<String> future = executorService.submit(new Callable<String>() {
        @Override
        public String call() throws Exception {
            return "hello world";
        }
    });

    System.out.println(future.get());//hello world
    executorService.shutdown();
}

发布了70 篇原创文章 · 获赞 1 · 访问量 2272

猜你喜欢

转载自blog.csdn.net/caozp913/article/details/103465126