保持java应用程序的单例实例

Kar*_*yan 3 java swing single-instance jframe

我有一个jar文件,显示它JFrame何时执行.我不想允许重复执行我的Jar文件.每次创建框架之前,使用Java我想检查Jar是否已经在执行.如果我的应用程序 我已经在屏幕上有一个实例,我想把它带到前面.

我怎样才能做到这一点?请建议我一个方法.

Cha*_*uni 7

对于应用程序的单个实例,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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

另外:它可以通过客户端将运行时参数传递到应用程序的主实例中Socket.因此,可以使主实例执行所需的任务,例如打开文件或播放音乐,方法InputStreamSocket在调用accept()方法时添加一些额外的代码来读取接受的内容.