这个我研究了两天,好多都是用的future.get(超时时间,单位)来实现,只是不同方式而已。下边来看下:
第一种:
//先新建一个 ExecutorService
ExecutorService exec = Executors.newSingleThreadExecutor();
//新建future,callable,call //返回值为String,任何类型都可以
FutureTask<String> future = new FutureTask<String>(
new Callable<String>() {
public String call() {
//需要定时检测的方法,写在此处
return "";
}
});
//加载future
exec.execute(future);
try {
//future的get()设定超时时间
String result = future.get(3900, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
future.cancel(true); //关闭future(关闭异常的监测方法)
// 做出对应异常的反应
} catch (ExecutionException e) {
future.cancel(true); //关闭future(关闭异常的监测方法 ,此异常标识方法内部异常)
// 做出对应异常的反应
} catch (TimeoutException e) {
future.cancel(true); //关闭超时线程
// 做出对应异常的反应
} finally {
exec.shutdown();
}
第二种:
//若线程超时关闭
ExecutorService exec = Executors.newFixedThreadPool(1);
//call(), 真正检测的方法体在此。
Callable<InterfaceUpdateDto> call = new Callable<InterfaceUpdateDto>() {
public InterfaceUpdateDto call() {
return ins.updateAndSelectByNodeId(dataj, nodeId);
}
};
Future<InterfaceUpdateDto> future = exec.submit(call);
try {
//future的get()设定超时时间
InterfaceUpdateDto interfaceUpdateDtoData = future.get(3900, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
future.cancel(true);
snmpList = ins.selectByNodeId(nodeId);
canCollect = "noCollect";
} catch (ExecutionException e) {
//因为在call()方法体内无法完成数据更新需要的数据库查询,遂再次再次更新操作
future.cancel(true);
InterfaceUpdateDto interfaceUpdateDto = ins.updateAndSelectByNodeId(dataj, nodeId);
snmpList = interfaceUpdateDto.getSnmpList();
canCollect = interfaceUpdateDto.getCanCollect();
} catch (TimeoutException e) {
future.cancel(true);
snmpList = ins.selectByNodeId(nodeId);
canCollect = "noCollect";
} finally {
exec.shutdown();
}
这几种都能实现,但是我需要定时检测的方法一在try中执行(一旦访问数据库)就会进入 异常,我debug调试了好久都没有找到原因,就暂时的找了一个解决办法 ——> 既然能正常检测超时,那我现在只要保证在不超时的情况下,正常进行我的方法就行了,我发现每次都会就入 异常,方法没执行完(跟新端口信息),于是我就将方法放到这个异常的catch{} 中,总之是完成了任务。