如何确保只运行Java应用程序的单个实例? [英] How to make sure that only a single instance of a Java application is running?

查看:127
本文介绍了如何确保只运行Java应用程序的单个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的应用程序检查其自身的另一个版本是否已在运行。

I want my application to check if another version of itself is already running.

例如, demo.jar 启动,用户点击再次运行它,但第二个实例意识到哦等等,已经有 demo.jar 正在运行。并退出并显示一条消息。

For example, demo.jar started, user clicks to run it again, but the second instance realizes "oh wait, there is already a demo.jar running." and quits with a message.

推荐答案

您正在寻找的内容可能最好通过锁定文件来完成。通过锁定文件,我只是指一个具有预定义位置并且其存在是您的互斥锁的文件。

What you are looking for can probably best be accomplished with a lock file. By lock file I simply mean a file that will have a predefined location and whose existence is your mutex.

在程序启动时测试该文件是否存在,如果存在,马上退出。在已知位置创建文件。如果程序正常退出,请删除锁定文件。

Test if that file exists when your program starts, if it does, exit immediately. Create a file in a known location. If your program exits normally, delete the lock file.

如果您还可以使用pid(进程ID)填充文件,那么最好的情况是,这样您就可以检测到没有删除文件的异常退出但是这个获取操作系统具体。

Probably best is if you can also populate the file with a pid (process id) so that you can detect abnormal exits that didn't delete the file but this get OS specific.

这篇关于如何确保只运行Java应用程序的单个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆