我正在开发一个Java程序,它同时打开命令行的多个实例。为此,我使用的线程为Runnable
s,如下所示:
//Handles the command line running
private Process p;
private String port;
private String path;
@Override
public void run() {
ProcessBuilder pb = //Initialization of ProcessBuilder
pb.directory(new File(this.path));
...
try {
p = pb.start();
p.waitFor(); //Using this since the server must continue after it is started.
... //This is the part I need to cancel when I close the thread.
}
} catch (IOException e) { //These exceptions are thrown from the process inside the Runnable.
...
} catch (InterruptedException e) {
...
}
}
public void stopServer() {
p.destroy();
}
在我的Main
应用程序类中:
ArrayList<Thread> threads = new ArrayList<>();
public void startServer(String port, String path) {
//Instantiate my Runnable Class, with port and path parameters
MyRunnable rss = new MyRunnable(port, path);
//Spawn a new thread with the Runnable
Thread thread = new Thread(rss);
//Set the name of the thread (presumably for finding it later?)
thread.setName("server-" + threads.size());
//Start the thread.
thread.start();
//Add the thread to an ArrayList<Thread>?
threads.add(thread);
}
所以我的问题是:如何使用我的stopServer()
方法停止Main类的进程?
免责声明:我对多线程编程非常陌生,所以你能给出的任何帮助都很棒,可能有些简单,我根本不知道Thread
的工作方式。
谢谢!
答案 0 :(得分:0)
而不是ArrayList<Thread>
,而是使用ArrayList<MyRunnable>
。
这样,如果对象不为null,我可以遍历调用stopServer()
的列表。