如果要使一个java Application只能运行一个实例。大多数会考虑使用JNDI技术来在命名空间中邦定特定的对象来做到该功能。
在windows下c开发的时候,这样的事情是很容易的,只需要创建一个信号量就可以了。
本文就是通过java的JNI技术来利用windows的信号内核对象的,从而非常容易的能控制一个java运行实例的数量的。
至于JNI技术就不多说了。
1。首先编写如下的java代码:/**方便起见,将所有的代码放在一个目录下
public class singleApp{
public native boolean findExsit();///native method
static { System.loadLibrary("singleApp");///load the native library }
public static void main(String []args) { boolean res=new singleApp().findExsit();
if(res) { System.out.println("find an instance"); System.exit(0); } else { System.out.println("this is no one exsit!"); } while(true) { } }
}
使用javac 编译得到类文件。
2.得到C的头文件
使用javah工具得到如下的头文件:singleApp .h
/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class singleApp */
#ifndef _Included_singleApp#define _Included_singleApp#ifdef __cplusplusextern "C" {#endif/* * Class: singleApp * Method: findExsit * Signature: ()Z */JNIEXPORT jboolean JNICALL Java_singleApp_findExsit (JNIEnv *, jobject);
#ifdef __cplusplus}#endif#endif
3.编辑c源文件:singleApp .cpp
#include <jni.h>#include <windows.h>#include <stdio.h>#include <singleApp.h>
JNIEXPORT jboolean JNICALL Java_singleApp_findExsit (JNIEnv *, jobject){ CreateSemaphore(NULL, 1, 1, "singleApp"); //创建信号量 if (GetLastError() == ERROR_ALREADY_EXISTS)//如果该信号量存在 return 1; else ///如果不存在 return 0;
}
然后使用C++编译器编译得到dll文件
我是使用的borland公司的c++命令行工具编译的。注意的java载入库的时候是使用的singleApp名字,所以我们的dll名字也要是一样的名字,就是singleApp.dll.
还要注意的该dll要放在java的类载入器能找到的地方,比如classpath指定的地方。
4.运行java程序
java singleApp
然后再开一个console窗口,运行该java程序,第2次运行的时候自动退出虚拟机的。
简单吧!