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

转: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 .classpath
2012-05-25  09:24               379 .project
2012-05-25  09:24    <DIR>          .settings
2012-05-25  15:05    <DIR>          bin
2012-05-25  11:26    <DIR>          lib
2012-05-25  15:03    <DIR>          src
2012-06-04  16:42    <DIR>          test
               2 个文件          1,038 字节
               7 个目录 134,112,276,480 可用字节
0
1
2
3
4
5
 */


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值