国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 灵川县| 武宁县| 迁西县| 内江市| 利津县| 伊金霍洛旗| 屏东县| 泉州市| 闽清县| 元江| 广州市| 昌平区| 福泉市| 沈阳市| 五大连池市| 琼结县| 广昌县| 紫云| 万盛区| 抚松县| 祁东县| 南木林县| 老河口市| 新源县| 特克斯县| 安溪县| 司法| 额敏县| 莆田市| 渭源县| 小金县| 鹿邑县| 阿巴嘎旗| 桑日县| 赤城县| 儋州市| 理塘县| 阳新县| 洛宁县| 乐清市| 朔州市|