运行java应用程序的一个实例

可能重复:
如何实现单实例Java应用程序?

有没有办法只运行一个Java应用程序实例,所以只有一个进程? 。 是不是可以在java中做到这一点?

拥有一个实例的简单方法是使用服务端口。

ServerSocket ss = new ServerSocket(MY_PORT); 

使用这种方法而不是锁定文件的好处是,您可以与已经运行的实例进行通信,甚至检查它是否正常工作。 例如,如果您无法启动服务器套接字,请使用普通套接字向其发送“为我打开文件”之类的消息

最简单的方法是在应用程序启动时在磁盘上创建一个锁定文件,如果文件不存在则正常运行。 如果文件存在,您可以假设应用程序的另一个实例正在运行并退出并显示一条消息。 假设我理解你的问题。

如果您的意思是“让您的应用程序的一个实例运行”然后是,您可以使用锁定文件来实现。 应用程序启动时,创建一个文件并在程序退出时将其删除。 在启动时,检查锁定文件是否存在。 如果文件存在,则只需退出,因为应用程序的另一个实例已在运行。

你可以在启动时打开一个套接字。 如果套接字正在使用中,则可能已经有一个应用程序实例正在运行。 锁定文件可以工作,但如果您的应用程序崩溃而没有删除锁定文件,则必须先手动删除该文件,然后才能再次启动应用程序。

您可以应用Singleton Pattern

Following are the ways to do it:

1.私有构造函数和同步方法

 public class MyClass{ private static MyClass unique_instance; private MyClass(){ // Initialize the state of the object here } public static synchronized MyClass getInstance(){ if (unique_instance == null){ unique_instance = new MyClass(); } return unique_instance; } } 

2. Private Constructor并在声明期间初始化静态实例

 public class MyClass{ private static MyClass unique_instance = new MyClass() ; private MyClass(){ // Initialize the state of the object here } public static MyClass getInstance(){ return unique_instance; } } 

3.仔细检查锁定

 public class MyClass{ private static MyClass unique_instance; private MyClass(){ // Initialize the state of the object here } public static MyClass getInstance(){ if (unique_instance == null) synchronized(this){ if (unique_instance == null){ unique_instance = new MyClass(); } } return unique_instance; } } 

You can also implement a class with 静态方法和静态变量 You can also implement a class with 以应用Singleton模式,但不推荐使用它