import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class SingleApplication {
// 在應用程序的main方法里調用此函數保證程序只有一個實例在運行.
public static void makeSingle(String singleId) {
RandomAccessFile raf = null;
FileChannel channel = null;
FileLock lock = null;
try {
// 在臨時文件夾創建一個臨時文件,鎖住這個文件用來保證應用程序只有一個實例被創建.
File sf = new File(System.getProperty("java.io.tmpdir") + singleId + ".single");
sf.deleteOnExit();
sf.createNewFile();
raf = new RandomAccessFile(sf, "rw");
channel = raf.getChannel();
lock = channel.tryLock();
if (lock == null) {
// 如果沒有得到鎖,則程序退出.
// 沒有必要手動釋放鎖和關閉流,當程序退出時,他們會被關閉的.
throw new Error("An instance of the application is running.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
SingleApplication.makeSingle("single.test"); // 保證程序只有一個實例在運行.
// 測試: 模擬一個程序正在運行5秒
System.out.println("Start");
System.out.println("Waiting 5 seconds.");
for (int i = 0; i < 5; ++i) {
Thread.sleep(1000);
System.out.println((i + 1) + "......");
}
System.out.println("End");
}
}