对于应用程序的单个实例,java中没有常规方法.
但是,您可以使用Socket编程技术来实现您的目标.
实例创建时,它会尝试侦听ServerSocket.如果它可以打开ServerSocket,则意味着没有该应用程序的另一个实例.因此,它会使ServerSocket保持活动状态,直到程序关闭.如果无法打开ServerSocket,则表示应用程序已经有另一个实例.因此,您可以静默退出应用程序.此外,关闭应用程序时无需重置设置.
试试下面的例子
public class SingletonApplication extends JFrame implements Runnable {
//count of tried instances
private int triedInstances = 0;
//the port number using
private static final int PORT = 5555;
public static void main(String[] args) {
SingletonApplication application = new SingletonApplication();
application.setTitle("My Singleton Application");
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setSize(500, 500);
application.setVisible(true);
}
public SingletonApplication() {
super();
//run socket listening inside a thread
Thread thread = new Thread(this);
thread.start();
}
@Override
public void run() {
try {
//create server socket
ServerSocket serverSocket = new ServerSocket(PORT);
//listing the socket to check new instances
while (true) {
try {
//another instance accessed the socket
serverSocket.accept();
//bring this to front
toFront();
//change the title (addtional);
triedInstances++;
setTitle("Tried another instances : " + triedInstances);
} catch (IOException ex) {
//cannot accept socket
}
}
} catch (IOException ex) {
//fail if there is an instance already exists
try {
//connect to the main instance server socket
new Socket(InetAddress.getLocalHost(), PORT);
} catch (IOException ex1) {
//do nothing
} finally {
//exit the system leavng the first instance
System.exit(0);
}
}
}
}
编辑:
另外:它可以通过客户端Socket将运行时参数传递给应用程序的主实例.因此,在调用accept()方法时,可以通过添加一些额外的代码来读取接受的Socket的InputStream,从而使主实例能够执行所需的任务,例如打开文件或播放音乐.