問題描述
這是我自己以前的問題的后續(xù)行動,我有點不好意思問這個......但無論如何:您將如何以獨立于系統(tǒng)的方式從獨立的 Java 程序啟動第二個 JVM?并且不依賴于例如像 JAVA_HOME 這樣的環(huán)境變量,因為它可能指向與當(dāng)前運行的 JRE 不同的 JRE.我想出了以下代碼,它確實有效,但感覺有點尷尬:
This is a followup to my own previous question and I'm kind of embarassed to ask this... But anyway: how would you start a second JVM from a standalone Java program in a system-independent way? And without relying on for instance an env variable like JAVA_HOME as that might point to a different JRE than the one that is currently running. I came up with the following code which actually works but feels just a little awkward:
public static void startSecondJVM() throws Exception {
String separator = System.getProperty("file.separator");
String classpath = System.getProperty("java.class.path");
String path = System.getProperty("java.home")
+ separator + "bin" + separator + "java";
ProcessBuilder processBuilder =
new ProcessBuilder(path, "-cp",
classpath,
AnotherClassWithMainMethod.class.getName());
Process process = processBuilder.start();
process.waitFor();
}
此外,當(dāng)前正在運行的 JVM 可能已使用第二個 JVM 不知道的其他一些參數(shù)(-D、-X...、...)啟動.
Also, the currently running JVM might have been started with some other parameters (-D, -X..., ...) that the second JVM would not know about.
推薦答案
我不清楚你是否總是希望使用完全相同的參數(shù)、類路徑或其他任何東西(尤其是 -X 類型的東西 - 例如,為什么要啟動輔助進(jìn)程時,子進(jìn)程需要與其父進(jìn)程相同的堆設(shè)置.
It's not clear to me that you would always want to use exactly the same parameters, classpath or whatever (especially -X kind of stuff - for example, why would the child need the same heap settings as its parents) when starting a secondary process.
我更愿意使用某種外部配置來為孩子定義這些屬性.這需要更多的工作,但我認(rèn)為最終你將需要靈活性.
I would prefer to use an external configuration of some sort to define these properties for the children. It's a bit more work, but I think in the end you will need the flexibility.
要查看可能的配置設(shè)置范圍,您可以查看 Eclipse 中的運行配置"設(shè)置.那里有相當(dāng)多的選項卡值得配置.
To see the extent of possible configuration settings you might look at thye "Run Configurations" settings in Eclipse. Quite a few tabs worth of configuration there.
這篇關(guān)于*this* 真的是從 Java 代碼啟動第二個 JVM 的最佳方式嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!