Callable与Future
Callable和Future,一个产生结果,一个拿到结果。
Callable接口类似于Runnable,但是Runnable不会返回结果,并且无法抛出返回结果的异常,而Callable功能更强大一些,被线程执行后,可以返回值,这个返回值可以被Future拿到,也就是说,Future可以拿到异步执行任务的返回值。
package com.itszt.test3; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; /** * Callable和Future */ public class Test4 { public static void main(String[] args) { Callable<String> callable = new Callable<String>() { @Override public String call() throws Exception { return new Random().nextInt(100)+""; } }; FutureTask<String> futureTask = new FutureTask<>(callable); new Thread(futureTask).start(); try { Thread.sleep(5000); System.out.println(futureTask.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }