线程与线程池笔记(二)Runnable,Callable,Future和FutureTask

Runnable,Callable,Future和FutureTask是什么?

我们上一篇讲了Thread的使用,发现可以继承Thread或实现Runnable来创建一个线程,两者都与Runnable脱不了关系。同时从下图可以发现,线程池的使用还可以执行Callable任务,这几和有什么关系呢?Future和FurureTask又是什么呢,下面看看吧。

首先我们发现线程池和线程可提交的任务都是Runnable和Callable:
在这里插入图片描述
我们先粘出Runnable和Callable和Future的代码看看

public interface Runnable {
    public abstract void run();
}
public interface Callable<V> {
    V call() throws Exception;
}
public interface Future<V> {

    /**
     * Attempts to cancel execution of this task.  This attempt will
     * fail if the task has already completed, has already been cancelled,
     * or could not be cancelled for some other reason. If successful,
     * and this task has not started when {@code cancel} is called,
     * this task should never run.  If the task has already started,
     * then the {@code mayInterruptIfRunning} parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.
     *
     * <p>After this method returns, subsequent calls to {@link #isDone} will
     * always return {@code true}.  Subsequent calls to {@link #isCancelled}
     * will always return {@code true} if this method returned {@code true}.
     *
     * @param mayInterruptIfRunning {@code true} if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return {@code false} if the task could not be cancelled,
     * typically because it has already completed normally;
     * {@code true} otherwise
     */
    boolean cancel(boolean mayInterruptIfRunning);

    /**
     * Returns {@code true} if this task was cancelled before it completed
     * normally.
     *
     * @return {@code true} if this task was cancelled before it completed
     */
    boolean isCancelled();

    /**
     * Returns {@code true} if this task completed.
     *
     * Completion may be due to normal termination, an exception, or
     * cancellation -- in all of these cases, this method will return
     * {@code true}.
     *
     * @return {@code true} if this task completed
     */
    boolean isDone();

    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     *
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     */
    V get() throws InterruptedException, ExecutionException;

    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

都是接口,而且只有需要实现的方法,不同的是 run()没有返回值,而call()可以有返回值还能抛出异常

Future没得什么run方法call方法,但却有一大堆任务的检查方法。方法名字都很能体现方法作用了,至于详细的,自己看下注释就能知道了。

所以说

  • 单独实现Runnable的任务只是埋头做,也不管什么时候做完,做没做完
  • 单独实现Callable的任务可以做完回一声你,如果做错了还能告诉你。
  • Future因为没有run方法call方法,所以会与Runnable和Callable配合,增强功能。
    FutureTask
public class FutureTask<V> implements RunnableFuture<V> {

实现了RunnableFuture

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

RunnableFuture继承了Future,和Runnable,所以说它和FutureTask都能够用作线程任务,而且验证了我们上面的说法。
我们看到RunnableFuture是个接口所以并没有实现run方法,交给我们的FutureTask实现了:

 public void run() {
        if (state != NEW ||
            !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

可以发现它又跑去执行Callable的call()方法,这个Callable是通过构造方法传递进来的(当然也可以传runnable,人家自己会帮你转成callable),所以说这个call()方法是我们需要手动实现的方法
看看我们平常怎么用FutureTask的吧

public class MyClass {
    public static void main(String[] args) {
        ExecutorService es = Executors.newSingleThreadScheduledExecutor();
        MyCallable myCallable = new MyCallable();

        FutureTask<String> myFutureTask = new FutureTask<String>(myCallable) {

            @Override
            public boolean cancel(boolean b) {
                return false;
            }

            @Override
            public boolean isCancelled() {
                return false;
            }

            @Override
            protected void done() {
                super.done();
            }
            @Override
            public boolean isDone() {
                return false;
            }
            @Override
            public String get() throws InterruptedException, ExecutionException {
                return null;
            }

            @Override
            public String get(long l, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
                return null;
            }
        };
        es.submit(myFutureTask);
        myFutureTask.cancel(true);

    }
}
class MyCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println("正在执行");
        return "执行完毕";
    }
}

FutureTask代码就几百行可以很快看完,大家去了解以下吧,这样更能加深记忆哦。有什么不好的地方请指出哦。

发布了16 篇原创文章 · 获赞 0 · 访问量 249

猜你喜欢

转载自blog.csdn.net/weixin_43860530/article/details/105309135