通过文件锁定达到java程序单进程

    public static void isInstanceRunning() {
        RandomAccessFile f = null;
        FileChannel fc = null;
        FileLock fl = null;
        try {
            File temp = new File("D:\lock.txt");
            File tempFolder = temp.getParentFile();
            if(tempFolder==null||!tempFolder.exists())
                tempFolder.mkdir();
            if(temp==null||!temp.exists())
                temp.createNewFile();
           
            f = new RandomAccessFile("D:\lock.txt", "rwd");
             fc = f.getChannel();
             fl = fc.tryLock();
             if(!fl.isValid()){
                 System.out.println("another instance is already running.");
                 System.exit(1);
             }

        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println("another instance is already running.");
            System.exit(1);
        }

     
    }

   把isInstanceRunning() 方法加入main方法的头一行,这样就可以阻止多进程了.

你可能感兴趣的:(java,F#)