java callable接口_Java Callable接口

一 理论

Runnable是执行工作的独立任务,但是不返回任何值。如果我们希望任务完成之后有返回值,可以实现Callable接口。在JavaSE5中引入的Callable是一个具有类型参数的范型,他的类型参数方法表示为方法call()而不是run()中返回的值,并且必须使用ExecutorService.submint()方法进行调用。

二 示例

//实现接口Callable 参数类型是String

public class TaskWithResult implements Callable {

private int id;

public TaskWithResult(int id){

this.id=id;

}

@Override

public String call() throws Exception {

return "result of TaskWithResult "+id;

}

}

//java测试方法,基于junit4

@Test

public void main2() {

ExecutorService exec= Executors.newCachedThreadPool();

//Future接口后面有源码

ArrayList> results=new ArrayList>();

long start=System.currentTimeMillis();

for(int i=0;i<10;i++){

results.add(exec.submit(new TaskWithResult(i)));

}

//System.out.println("====================cost:"+(System.currentTimeMillis()-start));

int count=0;

//遍历数据

for(Future fs:results){

//System.out.println("========cost:"+(System.currentTimeMillis()-start));

long start2=System.currentTimeMillis();

try{

//取数据

System.out.println(fs.get());

}catch (InterruptedException e){

System.out.print(e);

}catch (ExecutionException e){

System.out.print(e);

}finally {

exec.shutdown();

}

//System.out.println((count++)+"====================cost:"+(System.currentTimeMillis()-start2));

}

}

执行结果如下图:

170fd03ab724

result.png

三Callable接口源码

@FunctionalInterface

public interface Callable {

/**

* Computes a result, or throws an exception if unable to do so.

*

* @return computed result

* @throws Exception if unable to compute a result

*/

V call() throws Exception;

}

四 Future 接口源码

public interface Future {

//取消

boolean cancel(boolean mayInterruptIfRunning);

boolean isCancelled();

//任务是否完成

boolean isDone();

//获得数据

V get() throws InterruptedException, ExecutionException;

V get(long timeout, TimeUnit unit)

throws InterruptedException, ExecutionException, TimeoutException;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值