在
Callable接口
中,创建线程时,无论是继承Thread类、实现Runnable接口、继承Thread类、实现Runnable接口还是run () )另外,Runnable还有一个问题。 不能抛出例外。 run ) )方法中必须自己处理异常。
由于Runnable存在两个问题,因此产生了Callable接口和Future接口。 本节介绍了Callable接口和Future接口
Callable与Runnable不同,它提供call (方法。 可以看到,此方法具有返回值,可以抛出异常
要获取Callable返回值,需要FutureTask支持
公共接口可调用v {
//*
*计算a result,orthrowsanexceptionifunabletodoso。
*
* @返回计算结果
* @ throwsexceptionifunabletocomputearesult
*/
V call ) ) throws Exception;
}
使用ExecutorService运行Callable对象
tfuturetsubmit (呼叫标签任务;
看到此方法返回Future对象,Future对象是什么呢?
公共界面功能{
//请尝试在任务成功结束之前取消任务
布尔序列取消(布尔序列互连传输函数;
//如果在任务成功完成之前取消,isCancelled将返回true
布尔is cancelled (;
//检测任务是否已完成
布尔is done (;
//get方法将结果返回给调用方
V get ) ) throws InterruptedException,ExecutionException;
//get方法可以将结果返回给调用方,以限制限制超时时间
vget (长时间输出,时间单元单元) )。
throws InterruptedException,ExecutionException,TimeoutException;
}
FutureTask
FutureTask类同时提供了Runnable接口和Future接口,并具有异步和任务取消功能,因此可以创建可取消的任务示例:
公共类测试可调用{
publicstaticvoidmain (字符串[ ]数组) {
呼叫呼叫演示呼叫=new呼叫演示(;
futuretaskintegerfuturetask=newfuturetask (呼叫;
newthread(futuretask ).start );
特里
//get方法是一种阻止直到执行结束的方法
int sum=futureTask.get (;
system.out.println(--------);
system.out.println(sum;
} catch (中断执行)
e .打印堆栈跟踪(;
}
}
}
//*
* Callable与Runnable相比有返回值和异常
*/
classcalldemoimplementscallableinteger {
@Override
公共integer call () throws Exception { )。
int sum=0;
for (英制=0; i1000; I ) {2}
sum =i;
}
返回和;
}
}