[b]引言:[/b]
最近两次被网友问到,关于java运行dos命令的问题。一个是问能不能,一个是反映他写的程序执行结束后runtime.exec()才会被执行到。类似的这类被主线程策略影响的问题都可以果断往线程上想。
[b]正文:[/b]
话不多说,直接上代码。
这段就是runtime.exec(COMMAND)的一个例子。第2位仁兄,问到的问题,解决办法就在代码注释“(1)”处——让主线程让一次CPU时间。
这个跟JVM有关,简单地说,有个规则——thread.start()调用后,thread的run()不会被立即执行,而是通知JVM我thread可以执行了,进入等待状态了。
最近两次被网友问到,关于java运行dos命令的问题。一个是问能不能,一个是反映他写的程序执行结束后runtime.exec()才会被执行到。类似的这类被主线程策略影响的问题都可以果断往线程上想。
[b]正文:[/b]
话不多说,直接上代码。
/*
* 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可以执行了,进入等待状态了。