可能重复:
如何实现单实例 Java 应用程序?
有没有办法只运行一个 Java 应用程序实例,所以我只有一个进程?. 有可能在java中做到吗?
A simple way to have one instance is to use a service port.
ServerSocket ss = new ServerSocket(MY_PORT);
The benefit of using this approach instead of a locking a file is that you communicate to the instance already running and even check it is working. e.g. if you can't start the server socket use a plain Socket to send it a message like "open a file for me"
最简单的方法是在应用程序启动时在磁盘上创建一个锁定文件,如果文件不存在则正常运行。如果该文件确实存在,您可以假设您的应用程序的另一个实例正在运行并退出并显示一条消息。假设我理解你的问题是正确的。
如果您的意思是“让您的应用程序的一个实例正在运行”,那么是的,您可以使用锁定文件来实现这一点。当您的应用程序启动时,创建一个文件并在程序退出时将其删除。在启动时,检查锁定文件是否存在。如果文件存在,则退出,因为您的应用程序的另一个实例已经在运行。
You could open a socket on startup. If the socket is in use, there is probably already an instance of the app running. A lock file would work, but if your app crashes without deleting the lock file, you'll have to manually delete the file before you can start the app again.
您可以应用单例模式
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. 声明时私有构造函数和初始化静态实例
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
静态方法和静态变量应用单例模式,但不推荐。