一般使用线程池执行任务都是调用的execute方法,这个方法定义在Executor接口中:
public interface Executor {
void execute(Runnable command);
}
这个方法是没有返回值的,而且只接受Runnable。
那么像得到线程的返回值怎嘛办呢?
在ExecutorService接口中能找到这个方法:
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
这个方法接收两种参数,Callable和Runnable。返回值是Future。
下面具体看一下这些是什么东西。
Callable和Runnable
先看一下两个接口的定义:
Callable
public interface Callable<V> {
V call() throws Exception;
}
Runnable
interface Runnable {
public abstract void run();
}
和明显能看到区别:
1.Callable能接受一个泛型,然后在call方法中返回一个这个类型的值。而Runnable的run方法没有返回值
2.Callable的call方法可以抛出异常,而Runnable的run方法不会抛出异常。
Future
返回值Future也是一个接口,通过他可以获得任务执行的返回值。
定义如下:
public interface Future<V> {
boolean cancel(boolean var1);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long var1, TimeUnit var3) throws InterruptedException, ExecutionException, TimeoutException;
}
其中的get方法获取的就是返回值。
来个例子
submit(Callable task)
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(2);
//创建一个Callable,3秒后返回String类型
Callable myCallable = new Callable() {
@Override
public String call() throws Exception {
Thread.sleep(3000);
System.out.println("calld方法执行了");
return "call方法返回值";
}
};
System.out.println("提交任务之前 "+getStringDate());
Fu