带有返回值的任务
1. Runnable
和Callable<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();