Runnable、Callable、Future接口区别

    xiaoxiao2021-03-25  171

    我们分别看一下这三个接口的方法: 1、Runnable接口只有一个run()方法 ,并且该方法无返回值(我们相当熟悉)。 public interface Runnable { public abstract void run(); } 2、Callable接口也只有一个call()方法,但是该方法有具体的返回值。 public interface Callable<V> { V call() throws Exception; } 3、Future接口一共有五个方法。 public interface Future<V> { boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; } 我们先来分析一下Future的使用场景,Executor是Runnable和Callable的调度容器,Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果、设置结果操作,当get()方法被调用时,线程会阻塞,直到当前线程执行完成,释放锁。 (1)cancel()方法:如果取消任务成功则返回true,如果取消任务失败则返回false。 如果调用cancel()方法时,任务未执行,无论mayInterruptIfRunning为true或者false 都将返回true; 如果调用cancel()方法时,任务执行已经完成,无论mayInterruptIfRunning为true或者false 都将返回false; 如果调用cancel()方法时,任务正在执行,如果mayInterruptIfRunning为true,,表示可以取消正在执行的任务,则任务将取消,返回值为true,反之如果mayInterruptIfRunning为false,则任务不会取消,返回值为false; (2)isCanceld()方法:表示任务是否已经完成,若任务完成,则返回true (3)isDone()方法:方法表示任务是否已经完成,若任务完成,则返回true (4)get()方法:用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回 (5)get(long timeout, TimeUnit unit)方法:用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null 因此Future一共提供三个功能 1、取消任务 2、判断任务状态(是否已取消、是否已完成) 3、获取任务执行的结果 具体内容今天晚上继续更新......
    转载请注明原文地址: https://ju.6miu.com/read-7410.html

    最新回复(0)