Callable、Future和FutureTask

2020-04-03  本文已影响0人  卡路fly

Callable

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

Runnable

Callable与Runnable作用一样,区别在于Callable有返回值,并且出现异常能抛出来。

 @FunctionalInterface
public interface Runnable {
    public abstract void run();
}

FutureTask

FutureTask是Future接口的一个唯一实现类。

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();
}

Future

Future根据源代码解释其作用是对Callable或者Runnable进行管理,取消、检测完成与否获取最终结果等。

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;
}

示例Demo:

package FutureTaskCallable;

import java.util.concurrent.*;

class FutureTaskDemo {
    public static void main(String[] args) {
        // 创建一个ExecutorService对象
        ExecutorService executor = Executors.newCachedThreadPool();
        // new 一个Callable实例
        Task task = new Task();
        // new一个
        FutureTask<Integer> futureTask = new FutureTask<>(task);
        // 提交futureTask对象进入线程池
        executor.submit(futureTask);
        // 关闭线程池
        executor.shutdown();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        System.out.println("主线程在执行任务");

        try {
            // 获取futuretask结果
            System.out.println("task运行结果" + futureTask.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("所有任务执行完毕");
    }


    public static class Task implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            System.out.println("子线程在进行计算");
            Thread.sleep(3000);
            int sum = 0;
            for (int i = 0; i < 100; i++) {
                sum += i;
            }
            return sum;
        }
    }
}

上一篇 下一篇

猜你喜欢

热点阅读