qileilove

blog已经转移至github,大家请访问 http://qaseven.github.io/

Java程序运行超时后退出或进行其他操作的实现

 当程序进入死循环或者由于其他原因无法自行终止的时候,就需要强制退出程序了。
  对于开发软件 Eclipse ,在程序执行超时后,可以点击 Terminate 按钮强制退出。
  那么,我们可不可以通过程序设置一定的时间,当程序运行超过该时长后自行终止或者进行其他操作呢?
  查了大量资料后发现,Future类就能满足这个需求。
  Future类中重要方法包括get()和cancel()。
  get()获取数据对象,如果数据没有加载,就会阻塞直到取到数据,而 cancel()是取消数据加载。
  另外一个get(timeout)操作,表示如果在timeout时间内没有取到就失败返回,而不再阻塞。
  通过这些方法即可实现我们要求。
  Java 代码示例:
final ExecutorService exec = Executors.newFixedThreadPool(1);
Callable call = new Callable() {
public String call() throws Exception {
// 放入耗时操作代码块
int cash = 300;
String name = "张三";
System.out.println(name + "现在有" + cash + "元存款");
User u = new User(name, cash);
String[] arr = { "线程A", "线程B", "线程C", "线程D", "线程E", "线程F",
"线程G", "线程H", "线程I", "线程J" };
for (int i = 0; i < 10; i++) {
MyThread th = new MyThread(arr[i], u,
(int) (Math.random() * 1000 - 500));
th.start();
}
//耗时代码块结束
Thread.sleep(1000 * 5);
return "线程执行完成";
}
};
try {
Future future = exec.submit(call);
String obj = future.get(1000 * 1, TimeUnit.MILLISECONDS); // 任务处理超时时间设为1 秒
System.out.println("任务成功返回:" + obj);
} catch (TimeoutException ex) {
System.out.println("处理超时啦....");
System.exit(0);
} catch (Exception e) {
System.out.println("处理失败.");
e.printStackTrace();
}
exec.shutdown(); // 关闭线程池
将耗时的代码块放入标注的地方后,即可满足要求。
System.out.println("处理失败.");
e.printStackTrace();
System.out.println("处理失败.");
e.printStackTrace();
  在该示例程序中,当运行超时后,执行的是退出程序的操作。
  也可以根据需要放入其他代码进行相关操作。
  例如可以设置当处理超时时就忽略 该错误继续向下执行

posted on 2013-09-27 10:36 顺其自然EVO 阅读(193) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 
<2013年9月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

导航

统计

常用链接

留言簿(55)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜