gpt4 book ai didi

Java操作系统进程队列

转载 作者:行者123 更新时间:2023-11-30 01:39:17 24 4
gpt4 key购买 nike

我正在使用 native ProcessBuilder 类来创建可变大小的流程对象列表。目前,我只是在每个 Process 实例上调用 start 方法来滚动列表。然而,我希望通过将正在运行的进程的数量限制为自定义值(例如处理器的数量)来更好地控制应用程序的这方面。什么数据结构、现有库或模型最适合此任务?

Example

List<Process> processList = new ArrayList<Process>();
ProcessBuilder pb1 = new ProcessBuilder("myCommand", "myArg1", "myArg2");
ProcessBuilder pb2 = new ProcessBuilder("myCommand", "myArg1", "myArg2");
processList.add(pb1);
processList.add(pb2)

for(Process p : processList)
(
// more control is needed here
p.start();
}

最佳答案

使用ThreadPoolExecutor。一个简单的例子:

public class PBTest {

static List<Runnable> list = new ArrayList<Runnable>();

public static void main(String args[]) {
ProcessBuilder pb1 = new ProcessBuilder("foo.exe");
ProcessBuilder pb2 = new ProcessBuilder("foo.exe");
ProcessBuilder pb3 = new ProcessBuilder("foo.exe");
addPB(pb1);
addPB(pb2);
addPB(pb3);

ExecutorService ex = Executors.newFixedThreadPool(1);
for (Runnable r : list) {
System.out.println("calling execute");
ex.execute(r);
}

ex.shutdown();
}

static void addPB(final ProcessBuilder pb) {
list.add(new Runnable() {
public void run() {
try {
pb.start();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
}

}

关于Java操作系统进程队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1493040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com