我正在重新处理一个可能会多次启动的Java可执行文件,我希望这个过程一次只执行一个。在C#中,我可以使用命名/系统Mutex来实现这一点,但在Java语言中,这似乎是不可能的。如何实现此功能?
发布于 2019-04-08 19:08:57
在我看来,这种情况可以用Singleton设计模式来解决。在Windows中使用C时,我通过使用MutexCreateGlobal()调用解决了这个问题。在使用OOP语言(即Java)时,修改后的Singleton设计模式似乎可以做到这一点。
public class Singleton {
// **** members ****
private static Singleton singleInstance = null;
private static Semaphore sem = new Semaphore(1);
public int val = 0;
// **** constructor ****
private Singleton() {
val = 0;
}
// **** get instance of this class ****
public static Singleton getInstance() {
// **** request access ****
try {
sem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
// **** instantiate this class (if needed) ****
if (singleInstance == null) {
// **** instantiate Singleton ****
singleInstance = new Singleton();
// **** inform user what is going on ****
System.out.println("hashCode: " + singleInstance.hashCode());
}
// **** release access ****
sem.release();
// **** return this class ****
return singleInstance;
}
}https://stackoverflow.com/questions/3194227
复制相似问题