Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help on JNI calling java as a seperate thread.

Status
Not open for further replies.

wminghao

Programmer
May 29, 2000
24
US
Hi,

I made a screensaver which loads a jvm, forks a thread running a java class, wait until user's action(i.e. mouse move/click keyboard input), then terminate the java thread.

However, I met a problem, How to terminate a running java thread from c++ code?

Here is my code, but it does not work: (even after the terminate is called, jvm throws an error)

JNIEnv* env;
JavaVM* jvm;
HANDLE hThread; //handle for the startThread
unsigned __stdcall startThread(void *arg)
{
jclass cls;
jmethodID mainId;
jint res;
int threadNum = (int)arg;

res = jvm->AttachCurrentThread((void**)&env, NULL);
cls = env->FindClass( MAIN_CLASS);
mainId = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");

// setup the parameters to pass to main()
jstring str;
jobjectArray args;
int i=0;
args = env->NewObjectArray(1, env->FindClass("java/lang/String"), 0); //only one input parameters
str = env->NewStringUTF("localhost");
env->SetObjectArrayElement(args, 0, str);

env->CallStaticVoidMethod(cls, mainId, args); // call main()

if (env->ExceptionOccurred()) {
env->ExceptionDescribe();
}
return TRUE;
}

Here is the main method:
First create the jvm and load the thread. then tries to terminate the thread, but failed here
switch (msg)
{ case WM_CREATE:
JavaVMOption options[NUMBEROFOPTIONS];
JavaVMInitArgs vmargs;
jint rc;
vmargs.version = JNI_VERSION_1_4; /* version 1.4 */
vmargs.options = options;
vmargs.nOptions = NUMBEROFOPTIONS;
vmargs.ignoreUnrecognized = JNI_FALSE;
rc=JNI_CreateJavaVM( &jvm, (void **)&env, &vmargs ); /* create JVM */

/* We pass the thread number as the argument to the invoked thread */
unsigned int threadId = -1;

// to initialize a thread-safe C runtime library
hThread = (HANDLE)_beginthreadex(NULL, 0, &startThread, NULL, 0, &threadId );
} break;
case (WM_DESTROY):
{
CloseHandle( hThread );
jvm->DestroyJavaVM(); /* kill JVM */
Debug("Destroy Java Virtual Machine\n");
}break;
}

Note, after the thread "startThread" runs, it has an infinite loop and will not terminate, until the user clicks to terminate.(I didn't call jvm->DetachCurrentThread();_endthreadex(0); in the "startThread" because the java thread will not terminate by itself)
Thus, the only way to terminate the thread is to call closehandle(hthread) in the main thread, which may cause jvm to throw an error.

Do you know how to terminate a java thread safely???

Thanks a lot
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top