要在Java中連續運行兩個程序,你可以使用Java的進程調用功能來實現。具體步驟如下:
ProcessBuilder
類創建第一個程序的進程。ProcessBuilder pb1 = new ProcessBuilder("java", "Program1");
Process p1 = pb1.start();
int exitCode1 = p1.waitFor();
ProcessBuilder
類創建第二個程序的進程。ProcessBuilder pb2 = new ProcessBuilder("java", "Program2");
Process p2 = pb2.start();
int exitCode2 = p2.waitFor();
完整的示例代碼如下:
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
// 創建第一個程序的進程
ProcessBuilder pb1 = new ProcessBuilder("java", "Program1");
Process p1 = pb1.start();
// 等待第一個程序運行結束
int exitCode1 = p1.waitFor();
// 創建第二個程序的進程
ProcessBuilder pb2 = new ProcessBuilder("java", "Program2");
Process p2 = pb2.start();
// 等待第二個程序運行結束
int exitCode2 = p2.waitFor();
System.out.println("Program1 exit code: " + exitCode1);
System.out.println("Program2 exit code: " + exitCode2);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
請注意,上述代碼假設你的兩個程序Program1
和Program2
已經編譯并可在命令行中運行。你需要根據你自己的程序路徑和名稱進行相應的修改。