今天在项目开发中需要用到对执行方法加上时间控制,如果方法执行过长则跳出执行,废话不说,直接上代码,用的是线程池配合Callable和Future方式对执行方法的超时阻断。希望各位牛人指正
//启用线程池
final ExecutorService exec = Executors.newFixedThreadPool(1);
Callable<Map<String, String>> call = new Callable<Map<String, String>>(){
public Map<String, String> call() throws Exception {
Map<String,String> excuteMap = new HashMap<String,String>();
excuteMap = sendSSHSYS(servicePC, arrPort);//在这里执行相应的业务逻辑,要注意call里使用的参数是final的
return excuteMap;
}
};
Future<Map<String, String>> future = exec.submit(call);
try {
//20秒超时,这里是取出call中的返回值,如果在时间内仍然没有执行完毕的话,返回null
map=future.get(20, TimeUnit.SECONDS);
} catch (InterruptedException e) {
} catch (ExecutionException e) {
} catch (TimeoutException e) {
}
//在这下面就可以对map进行处理,如果map是null就说明是执行时间过长而阻断了。