首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

关闭程序施行直到程序运行完

2012-10-10 
关闭程序执行直到程序运行完Runtime.getRuntime().addShutdownHook(new Thread());程序正常或非正常时一定

关闭程序执行直到程序运行完

Runtime.getRuntime().addShutdownHook(new Thread());程序正常或非正常时一定会执行的方法,通过这个方法可以让程序在关闭前执行相应的操作。

下面是在关闭程序前一定要执行完代码再关闭的程序。

import java.io.BufferedReader;import java.io.InputStreamReader;public class ShMain extends Thread {  @SuppressWarnings("static-access")  public void run(){    while (!this.isInterrupted()) {      try {        System.out.println("hello10秒前");        this.sleep(1000*10);        System.out.println("hello10秒后");        this.sleep(1000*10);        System.out.println("hello20秒后");        if (!isRun) {          Runtime.getRuntime().exit(0);        }      }      catch (InterruptedException e) {        e.printStackTrace();      }    }  }  boolean isRun = true;  public void stopThread(){    isRun = false;  }   public static void main(String[] args) {    System.out.println("helloMain");    ShMain sh = new ShMain();    sh.start();    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));    String line;    try{      while(true){        line = br.readLine();//判断是否是exit        if(line.equals("exit")){          sh.stopThread(); //结束线程          break;        }      }    }catch(Exception e) {}  }}

?

热点排行