带有返回值的任务

1. RunnableCallable<v>对比

两者都是任务的抽象类,不同的是前者不会返回值,后者有返回值。两者源码如下:

  • Runnable
@FunctionalInterface
public interface Runnable {
    public abstract void run();
}
  • Callable<V>
@FunctionalInterface
public interface Callable<V> {
    V call() throws Exception;
}
2.Callable<V> 和Future<V>使用示例

ExecutorService threadPoolExecutor=Executors.newCachedThreadPool();
        
Future<Integer> future=threadPoolExecutor.submit(()->{ return 1; });
System.out.println(future.get());

threadPoolExecutor.shutdown();

posted on 2018-04-21 14:05  coderDu  阅读(238)  评论(0编辑  收藏  举报