h2 { margin-top: 0.46cm; margin-bottom: 0.46cm; line-height: 173%; page-break-inside: avoid; }h2.western { font-family: "Arial",sans-serif; font-size: 16pt; }h2.cjk { font-family: "黑体","SimHei"; font-size: 16pt; }h2.ctl { font-family: "DejaVu Sans"; font-size: 16pt; }h3 { margin-top: 0.46cm; margin-bottom: 0.46cm; line-height: 173%; page-break-inside: avoid; }h3.western { font-family: "DejaVu Serif",serif; font-size: 16pt; }h3.cjk { font-family: "DejaVu Sans"; font-size: 16pt; }h3.ctl { font-family: "DejaVu Sans"; font-size: 16pt; }p { margin-bottom: 0.21cm; }a:link { color: rgb(0, 0, 255); }
System 类
System
exit (int status)
终止当前正在运行的 Java 虚拟机。 如果因为异常而需要停止虚拟机 传入一个非零值 如果在用户正常使用下 需要传入一个0
currentTimeMillis ()
返回以毫秒为单位的由1970 年到现在的时间。
RunTime 类
RunTime 用来调用系统进程
getRuntime ()
返回与当前 Java 应用程序相关的运行时对象。
exec ( String [] cmdarray, String [] envp)
在指定环境的独立进程中执行指定命令和变量。
下面例子为调用 windows 记事本 执行 context.conf 文件
public static void main(String[] args) {
// 定义一个进程
Process p = null ;
try {
// 让进城运行 notepad.exe 运行 context.conf 文件
p = Runtime. getRuntime ().exec( "notepad.exe context.conf" );
// 线程停止 5 秒
Thread. sleep (5000);
// 销毁
p.destroy();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception ex){
ex.printStackTrace();
}
}
Timer 类和TimerTack 类
Timer 最长用的时让他隔多久后启动一个任务线程
schedule ( TimerTask task, Date time)
安排在指定的时间执行指定的任务。
TimerTack 一般用从写它的 run 方法获得一个线程对象
使用实例 隔 3 秒后自动打开 windows 中的计算器 退出 java 虚拟机(停止 java 程序)
public static void main(String[] args) {
/*
定时 3 秒后所要执行的代码 定义一个 TimeTask 子类 在子类中定义了父类的 run 方法 在 run 方法中启动执行 cale 的程序
到了设定时间之后就会执行 TimeTask 子类调用子类
Timer 默认不是后台线程 Daemon 这就意味着进程不能停止 如果想把他设置为后台线程就在定义 Timer 的时候传入一个参数 true 即 Timer(true)
当非 Demon 线程结束后 Daemon 线程就自动结束了 所以在此不能设置为 Daemon 因为 此代码在最后 如果设置为 Daemon 此代码就不能执行了 还未执行就结束线程了
*/
class MyTimerTask extends TimerTask{
private Timer tm ;
public MyTimerTask(Timer tm){
this . tm =tm;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
Runtime. getRuntime ().exec( "calc.exe" );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 结束任务线程的代码
tm .cancel();
}
}
Timer tm = new Timer();
// 创建一个线程 在 3000 毫秒后才去调用线程方法 调用 MyTimerTask 线程方法
tm.schedule( new MyTimerTask(tm), 3000);
}