【发布时间】:2016-02-02 16:47:20
【问题描述】:
我想同时执行一个 cmd 命令五次。所以我创建了一个执行命令的线程并启动了该线程五次。这是正确的吗?
MyRunnable r1 = new MyRunnable();
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
executor.execute(r1);
}
.......
@Override
public void run()
{
try {
// Execute command
String command = "cmd /c start cmd.exe";
Process child = Runtime.getRuntime().exec(command);
// Get output stream to write from it
OutputStream out = child.getOutputStream();
out.write("cd C:/ /r/n".getBytes());
out.flush();
out.write("dir /r/n".getBytes());
out.close();
} catch (IOException e)
{
}
}
【问题讨论】:
-
你有什么问题?
-
我不相信。执行时间本身需要时间。如果我没记错的话,启动一个正常的线程大约需要 2 秒
-
那么线程执行n次的正确方法是什么?
-
@seriously 有用吗?
-
@Kayaman 相反:我没有文件可以保证它。它只是保证它将为我执行代码,但不保证执行方式、顺序等。如果任务非常快,它们可能会在 1 个线程中结束。
标签: java multithreading executorservice