Runnbale封装一个异步运行的任务,可以把它想象成一个没有任何参数和返回值的异步方法。
Callable和Runnable相似,但是它有返回值。Callable接口是参数化的类型,只有一个方法call()
public interface Callable<V> {
V call() throws Exception;
}
类型参数就是返回值的类型,例如:Callable<String>表示最终返回一个String的异步操作(计算)。
Futrue是保存异步计算结果。当使用Future时,你就启动一个计算,把这个计算交给某个线程,然后你就去干别的事情了,比如喝杯咖啡。Future的拥有者就可以在他计算好以后得到他。
Future接口有以下方法
public interface Future<V> {
V get() throws ...;
V get(long timeOut, TimeUtil timeUtil) throws ...;
void cancel(boolean mayInterrput);
boolean isCancelled();
boolean idDone();
}
第一个get方法调用会被阻塞,直到计算完成;第二个get方法如果在计算完成之前超时,会抛出TimeOutException。如果运算线程被中断,这两个方法都会抛出InterruptedException。如果计算完成,get方法会立即返回。
你可以调用cancel来取消任务。如果任务已完成、或已取消,或者由于某些其他原因而无法取消,则此尝试将失败。当调用 cancel 时,如果调用成功,而此任务尚未启动,则此任务将永不运行。如果任务已经启动,则mayInterrput参数确定是否应该以试图停止任务的方式来中断执行此任务的线程。mayInterrput:如果应该中断执行此任务的线程,则为true;否则允许正在运行的任务运行完成。常常因为任务已经正常完成又调用该方法,方法会返回false。
boolean isCancelled() 如果在任务正常完成前将其取消,则返回 true
boolean isDone()如果任务已完成,则返回 true。 可能由于正常终止、异常或取消而完成,在所有这些情况中,此方法都将返回true
FutureTask包装器是一种很方便的把Callable转换成Future和Runnable的机制。因为他实现这两个接口,例如:
Callable<Integer> myComputation = ...;
FutureTask<Integer> task = new FutureTask<Integer>(myComputation );
Thread t = new Thread(task); //表现为Runnable
t.start();
...
Integer result = tesk.get(); //表现为Future
利用Callable和FutureTask来对redis 的 connect与否进行判断的例子:
public InspectStatus checkStatus() {
//定义Callable接口
Callable<Boolean> task = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
jedis.get("key");
jedisPool.returnResource(jedis);
} catch (RuntimeException e) {
logger.error("connection of jedis is error", e);
if( jedis != null ) {
jedisPool.returnBrokenResource(jedis);
}
return false;
}
return true;
}
};
//定义FutureTask类的对象,FutureTask类继承了Future<T>和Runnable接口
//在其中分别调用run和get方法
FutureTask<Boolean> ft = new FutureTask<Boolean>(task);
Boolean result;
try {
ft.run();
result = ft.get(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error("task has been interrupted");
return new InspectStatus(InspectErrorCodeConstant.REDIS_CONNECTION_ERROR_CODE, "task has been interrupted", getAlarmLevel());
} catch (ExecutionException e) {
logger.error("ExecutionException: " , e);
return new InspectStatus(InspectErrorCodeConstant.REDIS_CONNECTION_ERROR_CODE, "run task eccurs error " + e.getMessage(), getAlarmLevel());
} catch (TimeoutException e) {
logger.error("jedis connection timeout.", e);
return new InspectStatus(InspectErrorCodeConstant.REDIS_CONNECTION_ERROR_CODE, "jedis connection timeout.", getAlarmLevel());
}
if( result ) {
return OK;
} else {
logger.error("jedis connection error.");
return new InspectStatus(InspectErrorCodeConstant.REDIS_CONNECTION_ERROR_CODE, "jedis connection error.", getAlarmLevel());
}
}