java future callable_【Java并发核心五】Future 和 Callable

默认情况下,线程Thread对象不具有返回值的功能,如果在需要取得返回值的情况下会极为不方便。jdk1.5中可以使用Future 和 Callable 来获取线程返回值。

Callable 可以 看成与 Runnable 一样的但是有返回值的接口。

Callable接口的call()方法有返回值,而Runnable接口的run方法没有返回值;

Callable接口的call()方法可以声明抛出异常,而Runnable接口的run方法不可以声明抛出异常。

执行完Callable接口中的任务后,返回值是通过Future接口进行获取的。

看例子:

final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

ExecutorService executorService=Executors.newCachedThreadPool();//ExecutorService executorService = Executors.newFixedThreadPool(3);

List> futureList = new ArrayList>();//此线程池运行5个线程

for (int i = 0; i < 5; i++) {final int index =i;//使用 submit 方法 和 execute 方法的区别是,execute 方法没有返回值,而 submit 方法有返回值。

Future future = executorService.submit(new Callable() {

@Overridepublic String call() throwsException {

System.out.println("Thread-" + index + "-begin-" + sf.format(newDate()));try{

Thread.sleep(1000);

}catch(InterruptedException e) {

e.printStackTrace();

}

System.out.println("Thread-" + index + "-end-" + sf.format(newDate()));return "index-" +index;

}

});

futureList.add(future);

}//future.get() 是阻塞执行的,所以获取值要在线程都启动之后,再获取

for (Futurefuture : futureList) {try{

System.out.println(future.get());//获取线程返回值

} catch(InterruptedException e) {

e.printStackTrace();

}catch(ExecutionException e) {

e.printStackTrace();

}

}

ExecutorService 的 submit 方法 和 execute 方法的区别是,

execute 方法没有返回值,不能直接捕获异常,但可以通过自定义ThreadFactory的方式捕获异常;

submit 方法有返回值,可以直接使用 catch Execution-Exception捕获异常。

Future 的常用api:

get()    获取线程返回值,阻塞执行

get(long timeout, TimeUnit unit)    获取线程返回值(有超时时间),阻塞执行

cancel(boolean mayInterruptIfRunning)    取消执行,入参为true表示,如果线程正在运行则中断执行;为false表示,如果线程没有在运行才中断继续执行;返回值表示取消执行命令是否成功完成

isCancelled()    是否已取消执行

isDone()    如果完成此任务,则返回true。完成可能是由于正常终止、异常或取消——在所有这些情况下,此方法将返回true。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值