[英]How to run a Java program multiple times without JVM exiting?
Suppose I have a Java program Test.class
, if I used the below script 假设我有一个Java程序
Test.class
,如果我使用下面的脚本
for i in 1..10
do
java Test
done
the JVM would exit each time java Test
is invoked. 每次调用
java Test
时JVM都会退出。
What I want is running java Test
multiple times without exiting the JVM, so that, the optimized methods in prior runs can be used by later runs, and possibly be further optimized. 我想要的是多次运行
java Test
而不退出JVM,因此,先前运行中的优化方法可以在以后的运行中使用,并且可能进一步优化。
为什么不编写一个重复调用要运行的程序入口点的Java程序?
Run this once 运行一次
java Run
The main Program calling your Test
class mulitple times. 主程序多次调用您的
Test
类。
class Run {
public static void main(String[] args) {
for(int i=0; i<10; i++){
Test.main(args);
}
}
}
public class RunTest
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
Test.main(args);
}
}
This should do it. 这应该做到这一点。 You can call the Test class' main function with the same arguments you pass to your main function.
您可以使用传递给main函数的相同参数调用Test类的main函数。 This is the "wrapper" that another poster referred to.
这是另一张海报提到的“包装纸”。
Use code like this: 使用这样的代码:
public static void main2(String args[]){ // change main to main2
for(int i=0;i<10;i++)main(args);
}
public static void main(String args[]){ // REAL main
//...
}
Perhas a ProcessBuilder
would be suitable? Perhas一个
ProcessBuilder
会适合吗? Eg, something like 比如,像
String[] cmd = {"path/to/java", "test"};
ProcessBuilder proc = new ProcessBuilder(cmd);
Process process = proc.start();
What you want to do is put the loop inside the Test
class or pass the number of times you want to loop as an argument to the main()
inside Test
. 你想要做的就是把循环里面什么
Test
类或传递要循环的次数作为参数传递给main()
内部Test
。
NOTE: 注意:
If you are looking at JIT optimizations it will take more than 10 iterations to kick in. 如果您正在考虑JIT优化,则需要超过10次迭代才能启动。
Same as previous examples but using command line args 与前面的示例相同,但使用命令行参数
public class Test {
public static void main(String[] args) {
if ( args.length > 0) {
final Integer n = Integer.valueOf(args[0]);
System.out.println("Running test " + n);
if ( n > 1 ) {
main(new String[] { Integer.toString(n-1) });
}
}
}
}
use the args to indicate the number of runs 使用args指示运行次数
$ java Test 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.