控制一段程序的执行时间
注:限定一段代码执行的时间,超时自动结束线程
final ExecutorService exec = Executors.newFixedThreadPool(1);
//限定执行时间处理
Callable<String> call2 = new Callable<String>() {
public String call() throws Exception {
//开始执行耗时操作 。。。。。。
//........................
return "线程执行完成.";
}
};
try {
Future<String> future = exec.submit(call2);
String obj = future.get(4*60*60, TimeUnit.SECONDS); //任务处理超时时间设为 4*60*60 秒
System.out.println(DateUtil.getTimestamp());
System.out.println("任务成功返回:" + obj);
log.info(DateUtil.getCurrentTime()+" 数据在规定的时间(4小时)内同步完成!");
} catch (TimeoutException ex) {
System.out.println(DateUtil.getTimestamp());
System.out.println("处理超时啦....");
log.error(DateUtil.getCurrentTime()+" (同步超时):"+ex.getMessage());
System.out.println(DateUtil.getTimestamp());
ex.printStackTrace();
} catch (Exception e) {
System.out.println("处理失败.");
e.printStackTrace();
}
// 关闭线程池 //最后关闭
exec.shutdown();