4.3调用系统进程和虚拟机

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);

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值