Java如何使用Callable获得线程返回值呢?
下文笔者讲述Callable获取线程返回值的方法分享
获取线程返回值的实现思路
1.通过Callable实现线程 2.使用future获取线程返回值例:获取线程返回值的示例
package com.java265; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; public class TestCallable { public static void main(String[] args) { //Callable,ExecutorService,Future ExecutorService executor = Executors.newCachedThreadPool(); Future<String> future = executor.submit(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(1000); return "abc"; } }); System.out.println("1..."); try { System.out.println(future.get());//阻塞等待返回 } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } //Callable,FutureTask,ExecutorService FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() { @Override public Integer call() throws Exception { return 12345; } }); executor.submit(futureTask); System.out.println("2..."); try { System.out.println(futureTask.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } //Callable,FutureTask,Thread FutureTask<Integer> futureTask2 = new FutureTask<Integer>(new Callable<Integer>() { @Override public Integer call() throws Exception { return 6789; } }); new Thread(futureTask2).start(); System.out.println("3..."); try { System.out.println(futureTask2.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。