java 如何重启
重启 Java 应用程序的方法
在 Java 中重启应用程序通常需要终止当前运行的实例并重新启动一个新的实例。以下是几种常见的实现方式:
使用 System.exit 和 Runtime.exec
通过调用 System.exit 退出当前程序,然后使用 Runtime.exec 启动一个新的进程。
public class RestartExample {
public static void main(String[] args) {
System.out.println("Application started");
try {
// 模拟程序运行
Thread.sleep(3000);
// 重启逻辑
String javaBin = System.getProperty("java.home") + "/bin/java";
String classpath = System.getProperty("java.class.path");
String className = RestartExample.class.getName();
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
builder.start();
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用外部脚本
创建一个外部脚本(如 shell 或批处理文件)来管理应用程序的启动和重启。
restart.sh (Linux/Mac)

#!/bin/bash
kill $(ps aux | grep 'java -jar your-app.jar' | awk '{print $2}')
java -jar your-app.jar
restart.bat (Windows)
@echo off
taskkill /f /im java.exe
java -jar your-app.jar
使用 Spring Boot Actuator
对于 Spring Boot 应用程序,可以通过 Actuator 端点实现重启。

-
添加依赖到
pom.xml:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> -
启用 shutdown 端点(在
application.properties中配置):management.endpoint.shutdown.enabled=true management.endpoints.web.exposure.include=shutdown -
通过 HTTP 请求触发重启:
curl -X POST http://localhost:8080/actuator/shutdown
注意事项
- 确保重启逻辑不会导致无限循环
- 考虑应用程序状态的持久化,避免数据丢失
- 在生产环境中使用更完善的进程管理工具(如 systemd 或 supervisor)






