Future
用于异步计算,可以获取异步计算结果、取消异步任务、判断任务是否被取消、是否执行完成。
1、get
get()用于获取异步计算结果,如果计算未完成,则阻塞当前线程,直到计算完成
task类
public class CallableTask implements Callable<String> { @Override public String call() throws InterruptedException { System.out.println(Thread.currentThread().getName() + " start."); Thread.sleep(3000); System.out.println(Thread.currentThread().getName() + " finished."); return "Callable Task return."; } }
测试类:
public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService service = Executors .newFixedThreadPool(1, new ThreadFactoryBuilder().setNameFormat("test-%d").build()); Future<String> future = service.submit(new CallableTask()); System.out.println("calc result: " + future.get()); System.out.println("Master run finished."); service.shutdownNow(); }
执行结果:
get(time, timeunit),表示等待有限度,如果超过指定时间未完成,抛出超时异常
测试类:
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException { ExecutorService service = Executors .newFixedThreadPool(1, new ThreadFactoryBuilder().setNameFormat("test-%d").build()); Future<String> future = service.submit(new CallableTask()); System.out.println("calc result: " + future.get(2, TimeUnit.SECONDS)); System.out.println("Master run finished."); service.shutdownNow(); }
执行结果: 可以看到,主进程抛出异常,线程执行完成
2、cancel
用来取消任务执行。如果任务执行完成,或者已经取消,或者由于未知原因不能取消,返回false;
如果任务未开始,则返回true,并且任务永远不能被执行;
如果任务已经开始执行,并且mayInterruptIfRunning指定为true,则中断该任务,否则允许任务执行完成 ----- 这里有点疑问,明天确认下
场景1:任务执行完成后取消任务,返回false
源码:
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException { ExecutorService service = Executors .newFixedThreadPool(1, new ThreadFactoryBuilder().setNameFormat("test-%d").build()); Future<String> future = service.submit(new CallableTask()); Thread.sleep(4000); System.out.println("Future is cancel succeed? " + future.cancel(false)); System.out.println("Master run finished."); service.shutdownNow(); }
执行结果:
场景2:任务执行中,返回true
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException { ExecutorService service = Executors .newFixedThreadPool(1, new ThreadFactoryBuilder().setNameFormat("test-%d").build()); Future<String> future = service.submit(new CallableTask()); Thread.sleep(1000); System.out.println("Future is cancel succeed? " + future.cancel(false)); System.out.println("Master run finished."); service.shutdownNow(); }
执行结果:
3、isCanceled
任务执行完成之前被取消,返回true
4、isDone
任务被终止、被取消、出现异常,该方法均会返回true