java高并发之hook实例(防止重复启动程序)

package com.test.testThread;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;

public class TestThread {

    private final static String LOCK_PATH = "D:/testest/";
    private final static String LOCK_FILE = "start_up.lock";
    private static boolean flag = false;
    private static File lockFile = getLockFile();

    // 获取锁文件
    private static File getLockFile() {
        return Paths.get(LOCK_PATH, LOCK_FILE).toFile();
    }

    public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.out.println("The program will end");
                if (flag)
                    lockFile.delete();
            }
        });
        // 检测锁文件是否存在,若存在,则抛出异常
        if (lockFile.exists()) {
            throw new RuntimeException("The program already exists");
        }
        try {
            // 锁文件不存在时,创建锁文件
            lockFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 模拟程序的运行
        int i = 0;
        while (i++ < 10) {
            try {
                flag = true;
                TimeUnit.SECONDS.sleep(2);
                System.out.println("The program is running");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}





 


特点:

在模拟程序的运行的时间范围内,无法再次启动本程序。

 

缺点:

本程序缺少中断时的处理。

你可能感兴趣的:(Java)