程序避免多次启动

程序避免多次启动方法:
1. 通过文件锁FileLock
加锁
    private boolean tryLockFile()
    {
        try
        {
            File lockFile = new File(LOCKFILEPATH);
            
            //文件不存在,创建文件失败时,返回
            if (!lockFile.exists() && (!lockFile.createNewFile()))
            {
                return false;
            }
            //隐藏锁文件
            String setHide = "attrib +H \"" + lockFile.getAbsolutePath() + "\"";
            Runtime.getRuntime().exec(setHide);
            
            ranStream = new RandomAccessFile(lockFile, "rw");
            
            fileLock = ranStream.getChannel().tryLock();
            
            if (null == fileLock)
            {
                return false;
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return false;
        }
        return true;
    }


解锁
private void releaseFileLock()
    {
        try
        {
            if (null != this.fileLock)
            {
                fileLock.release();
            }
            
            if (null != this.ranStream)
            {
                this.ranStream.close();
            }
            
            File lockFile = new File(LOCKFILEPATH);
            if (lockFile.exists())
            {
                lockFile.delete();
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(java)