Java程序運(yùn)行超時(shí)后退出或進(jìn)行其他操作的實(shí)現(xiàn)
當(dāng)程序進(jìn)入死循環(huán)或者由于其他原因無(wú)法自行終止的時(shí)候,就需要強(qiáng)制退出程序了。
對(duì)于開(kāi)發(fā)軟件 Eclipse ,在程序執(zhí)行超時(shí)后,可以點(diǎn)擊 Terminate 按鈕強(qiáng)制退出。
那么,我們可不可以通過(guò)程序設(shè)置一定的時(shí)間,當(dāng)程序運(yùn)行超過(guò)該時(shí)長(zhǎng)后自行終止或者進(jìn)行其他操作呢?
查了大量資料后發(fā)現(xiàn),F(xiàn)uture類(lèi)就能滿足這個(gè)需求。
Future類(lèi)中重要方法包括get()和cancel()。
get()獲取數(shù)據(jù)對(duì)象,如果數(shù)據(jù)沒(méi)有加載,就會(huì)阻塞直到取到數(shù)據(jù),而 cancel()是取消數(shù)據(jù)加載。
另外一個(gè)get(timeout)操作,表示如果在timeout時(shí)間內(nèi)沒(méi)有取到就失敗返回,而不再阻塞。
通過(guò)這些方法即可實(shí)現(xiàn)我們要求。
Java 代碼示例:
final ExecutorService exec = Executors.newFixedThreadPool(1); Callable call = new Callable() { public String call() throws Exception { // 放入耗時(shí)操作代碼塊 int cash = 300; String name = "張三"; System.out.println(name + "現(xiàn)在有" + 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(); } //耗時(shí)代碼塊結(jié)束 Thread.sleep(1000 * 5); return "線程執(zhí)行完成"; } }; try { Future future = exec.submit(call); String obj = future.get(1000 * 1, TimeUnit.MILLISECONDS); // 任務(wù)處理超時(shí)時(shí)間設(shè)為1 秒 System.out.println("任務(wù)成功返回:" + obj); } catch (TimeoutException ex) { System.out.println("處理超時(shí)啦...."); System.exit(0); } catch (Exception e) { System.out.println("處理失敗."); e.printStackTrace(); } exec.shutdown(); // 關(guān)閉線程池 將耗時(shí)的代碼塊放入標(biāo)注的地方后,即可滿足要求。 System.out.println("處理失敗."); e.printStackTrace(); System.out.println("處理失敗."); e.printStackTrace(); |
在該示例程序中,當(dāng)運(yùn)行超時(shí)后,執(zhí)行的是退出程序的操作。
也可以根據(jù)需要放入其他代碼進(jìn)行相關(guān)操作。
例如可以設(shè)置當(dāng)處理超時(shí)時(shí)就忽略 該錯(cuò)誤繼續(xù)向下執(zhí)行
posted on 2013-09-27 10:36 順其自然EVO 閱讀(206) 評(píng)論(0) 編輯 收藏