目前,当用户尝试多次运行 jar 时,我正在尝试显示一条弹出消息。 我当前的代码如下所示
public static void main(String[] args){
new ServerSocket(65535, 1, InetAddress.getLocalHost());// if there are already one
// running jar, it will prevent
// the program to execute
JOptionPane.showMessageDialog(frame, "Hello World \n"); //Display hello world message
// when run
}
当用户多次运行 jar 时的期望输出:
Your jar application is already running . . .
我的问题是,我们如何显示一条消息告诉用户 jar 应用程序已经在运行,因为 ServerSocket() 将阻止应用程序运行,所以我在之后放置的“已经运行”弹出消息将不会运行。
回答:
try{
new ServerSocket(65535, 1, InetAddress.getLocalHost());
JOptionPane.showMessageDialog(frame, "Hello World \n");
}
catch(BindException ex){
JOptionPane.showMessageDialog
(frame, "Your jar application is already running . . . \n");
System.exit(0);
}
最佳答案
一种常用的方法是在磁盘上创建一个文件说应用程序正在运行并在jar正常终止时删除该文件,在启动时检查文件是否存在并显示正确的消息,同时考虑jvm异常终止的情况
例如 eclipse 使用 .lock
文件锁定当前工作区
关于 java 。使用弹出消息 "already running"防止 Jar App 多次运行。 (使用 ServerSocket()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22600443/