java运行dos命令方法及不立即执行的解决

来源:互联网 发布:泉州五中网络平台 编辑:程序博客网 时间:2024/06/07 03:35

转:http://zhaoningbo.iteye.com/blog/1553314

引言:
    最近两次被网友问到,关于java运行dos命令的问题。一个是问能不能,一个是反映他写的程序执行结束后runtime.exec()才会被执行到。类似的这类被主线程策略影响的问题都可以果断往线程上想。

正文:
    话不多说,直接上代码。

 

/* * Copyright (c) 2010 CCX(China) Co.,Ltd. All Rights Reserved. * * This software is the confidential and proprietary information of * CCX(China) Co.,Ltd. ("Confidential Information"). * It may not be copied or reproduced in any manner without the express  * written permission of CCX(China) Co.,Ltd. * * Author: 赵宁勃 * Date: 2012-6-6 */package com.number.demo.test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;public class TestRuntimeExec {    public static void main(String[] args) {        // 线程里执行command命令        Thread t = new Thread() {            @Override            public void run() {                try {                    Process process = Runtime.getRuntime().exec("cmd /c dir");                    InputStream in = process.getInputStream();                    BufferedReader inr = new BufferedReader(                            new InputStreamReader(in, "GBK"));                    String line = null;                    while ((line = inr.readLine()) != null) {                        System.out.println(line);                    }                } catch (IOException e) {                    e.printStackTrace();                }            }        };        t.start();        try {            // (1)让主线程让一次CPU时间            Thread.sleep(200);        } catch (InterruptedException e) {            e.printStackTrace();        }        // 主线程继续做自己的事        for (int i = 0; i < 50; i++) {            System.out.println("" + i);        }    }}/*驱动器 D 中的卷是 D 卷的序列号是 CCD7-1C62 D:\workspace\tmp 的目录2012-05-25  14:59    <DIR>          .2012-05-25  14:59    <DIR>          ..2012-05-25  14:59               659 .classpath2012-05-25  09:24               379 .project2012-05-25  09:24    <DIR>          .settings2012-05-25  15:05    <DIR>          bin2012-05-25  11:26    <DIR>          lib2012-05-25  15:03    <DIR>          src2012-06-04  16:42    <DIR>          test               2 个文件          1,038 字节               7 个目录 134,112,276,480 可用字节012345 */


这段就是runtime.exec(COMMAND)的一个例子。第2位仁兄,问到的问题,解决办法就在代码注释“(1)”处——让主线程让一次CPU时间。
  这个跟JVM有关,简单地说,有个规则——thread.start()调用后,thread的run()不会被立即执行,而是通知JVM我thread可以执行了,进入等待状态了。