[英]Is there a reason to keep a reference to a Singleton instance in another class in Java?
[英]Keep singleton instance of java application
我有一個jar文件,在執行時顯示JFrame
。 我不想允許重復執行我的Jar文件。 每次創建框架之前,使用Java我想檢查Jar是否已經在執行。 如果我的應用程序 我已經在屏幕上有一個實例,我想把它帶到前面。
我怎樣才能做到這一點? 請建議我一個方法。
對於應用程序的單個實例,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
,從而使主實例能夠執行所需的任務,例如打開文件或播放音樂。
我有同樣的情況。
我做的是我曾經以write
模式打開file
,並在關閉應用程序時delete
file
。
通過這樣做,我有一個已知的證據,我的程序正在運行。
每次打開應用程序時,我都會檢查該文件是否存在,如果找到我的文件,它就會運行,然后我就會提醒他
“一個實例已經在運行”。
即使有人試圖刪除該文件,它也表示它已在另一個應用程序中打開。
我也通過RMI使用了套接字。
該應用程序是RMI主機/服務器,在端口上接受遠程方法調用。
在主要的,在啟動時嘗試作為RMI客戶端在該端口上獲取RMI服務器。 是否有人通過命令行args進行遠程調用(例如打開另一個文檔)。 然后退出。
作為被調用的服務器,遠程方法使用窗口的toFront()
將應用程序帶到前面。
JUnique完成了第一部分 - 阻止同一程序的多個實例。 讓現有實例走到前面是另一項我不確定如何處理的任務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.