国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

如何使用Runtime.addShutdownHook

2019-11-18 15:29:47
字體:
供稿:網(wǎng)友
    以前從未用過 Runtime.addShutdownHook(Thread), 也不知道什么是 shutdown hook.
最近剛剛接觸了一點(diǎn),總結(jié)一下。

根據(jù) java API, 所謂 shutdown hook 就是已經(jīng)初始化但尚未開始執(zhí)行的線程對(duì)象。在
Runtime 注冊(cè)后,假如 jvm 要停止前,這些 shutdown hook 便開始執(zhí)行。

有什么用呢?就是在你的程序結(jié)束前,執(zhí)行一些清理工作,尤其是沒有用戶界面的程序。

很明顯,這些 shutdown hook 都是些線程對(duì)象,因此,你的清理工作要寫在 run() 里。
根據(jù) Java API,你的清理工作不能太重了,要盡快結(jié)束。但仍然可以對(duì)數(shù)據(jù)庫進(jìn)行操作。

舉例如下:

  1. package john2;
  2. /**
  3.  * test shutdown hook
  4.  * All rights released and correctness not guaranteed.
  5.  */
  6. public class ShutdownHook implements Runnable {
  7.     
  8.     public ShutdownHook() {
  9.         // register a shutdown hook for this class.
  10.         // a shutdown hook is an initialzed but not started thread, which will get up and run
  11.         // when the JVM is about to exit. this is used for short clean up tasks.
  12.         Runtime.getRuntime().addShutdownHook(new Thread(this));
  13.         System.out.    }
  14.     
  15.     // this method will be executed of course, since it's a Runnable.
  16.     // tasks should not be light and short, accessing database is alright though.
  17.     public void run() {
  18.         System.out.println("/n>>> About to execute: " + ShutdownHook.class.getName() + ".run() to clean up before JVM exits.");
  19.         this.cleanUp();
  20.         System.out.println(">>> Finished execution: " + ShutdownHook.class.getName() + ".run()");

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 南丰县| 隆子县| 佳木斯市| 叙永县| 库伦旗| 盘锦市| 石家庄市| 手游| 呼和浩特市| 肥乡县| 海兴县| 土默特左旗| 哈密市| 临泉县| 隆尧县| 西峡县| 荥经县| 肃南| 兰考县| 汾阳市| 顺义区| 福贡县| 如东县| 上栗县| 昌乐县| 山东省| 罗定市| 临夏市| 南涧| 永春县| 广平县| 且末县| 平邑县| 辽中县| 尉犁县| 崇明县| 石林| 青海省| 独山县| 杭锦旗| 固原市|