How do I make sure only one instance of my program can be executed?

后端 未结 6 551
旧时难觅i
旧时难觅i 2021-01-07 01:17

I want my program, a Java executable .jar, to be run just once. I made a program but now I want users not to be able to open more than one instance ....thanks for your time.

6条回答
  •  说谎
    说谎 (楼主)
    2021-01-07 01:53

    You could use sockets - a ServerSocket can only listen on a port that's not already in use. The first launch successfully creates a ServerSocket instance on the port - while that program is running, no other ServerSocket can successfully be created on that port.

    import java.io.IOException;
    import java.net.ServerSocket;
    
    public class OneInstance {
    
        private static ServerSocket SERVER_SOCKET;
    
        public static void main(String[] args) {
            try {
                SERVER_SOCKET = new ServerSocket(1334);
                System.out.println("OK to continue running.");
                System.out.println("Press any key to exit.");
                System.in.read();
            } catch (IOException x) {
                System.out.println("Another instance already running... exit.");
            }
        }
    } 
    

提交回复
热议问题