java 线程池 返回值_Java多线程-线程池ThreadPoolExecutor的submit返回值Future

一般使用线程池执行任务都是调用的execute方法,这个方法定义在Executor接口中:

public interface Executor {

void execute(Runnable command);

}

这个方法是没有返回值的,而且只接受Runnable。

那么像得到线程的返回值怎嘛办呢?

在ExecutorService接口中能找到这个方法:

Future submit(Callable task);

Future submit(Runnable task, T result);

Future> submit(Runnable task);

这个方法接收两种参数,Callable和Runnable。返回值是Future。

下面具体看一下这些是什么东西。

Callable和Runnable

先看一下两个接口的定义:

Callable public interface Callable {

V call() throws Exception;

}

Runnable interface Runnable {

public abstract void run();

}

和明显能看到区别:

Callable能接受一个泛型,然后在call方法中返回一个这个类型的值。而Runnable的run方法没有返回值

Callable的call方法可以抛出异常,而Runnable的run方法不会抛出异常。

Future

返回值Future也是一个接口,通过他可以获得任务执行的返回值。

定义如下:

public interface Future {

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

Future future = executor.submit(myCallable);

System.out.println("提交任务之后,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值