停止调用JNI函数的Java线程 [英] Stop Java thread which call JNI function

查看:304
本文介绍了停止调用JNI函数的Java线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我想停止我的线程或杀死我在Java层上创建的线程,该线程正在调用JNI函数.有时,根据我的应用程序要求,如果发生这种情况,我必须在某些情况下停止此 JNI函数执行,否则就不会.

Here I want to stop my thread or kill my thread which is created on Java layer, and this thread is calling JNI function. Sometimes as per my application requirement, I have to stop this JNI function execution on some conditions if its going on, otherwise not.

new Thread(new Runnable() {
    @Override
    public void run() {
         // My jni function call, It calls my JNI layer C function.
         }
   }

现在,当该线程执行开始并且在JNI级别上进行工作时,我对此无后顾之忧,但是在某些情况下,从其他类或方法中,我想停止此JNI工作,那么如何停止该线程.

Now when this thread execution is started and its doing work at JNI level I have no worries about that, but from other class or methods on some condition I want to stop this JNI work so how can I stop this thread.

注意:在这里,我的线程也没有while循环,因此我也无法检查一些全局标志变量.

Note: Here my thread also has no while-loop so I cant check with some global flag variable also.

所以没有人知道如何在不使用while循环的情况下调用任何JNI函数时杀死线程.

So does anyone have an idea on how to kill a thread while its call any JNI function without while loop.

推荐答案

如果线程正在执行本机代码,则不能安全中断线程.即使您的线程有一个事件循环,您也需要等到它完成本机调用.对您的代码一无所知,我想您有一个运行时间很长的本机调用,您不希望它阻塞主线程,因此为该调用创建了一个单独的线程.您无法安全中断单个本地通话.这里没有银弹.无论如何,您都需要更改代码,我的建议是:

You can't safely interrupt a thread, if it is executing a native code. Even if your thread had an event loop, you need to wait until it finishes the native call. Knowing nothing about your code, i would guess that you had a long running native call, you didn't want it to clog the main thread, so you created a separate thread for that call. There is no way you can safely interrupt a single native call. No silver bullet here. You need to change your code in any case, my suggestions would be:

  • 将您的单个长本地调用分解为一系列短调用,并在Java端运行事件循环
  • 在本机端内部分解本机调用,并在本机端运行事件循环.您的本机界面将需要另一种设置中断标志的方法.

Thread.interrupt() 不会对您有帮助,因为调用本机函数"不属于Javadoc中指定的任何可中断操作. Java线程将继续运行,只设置其中断状态.

这篇关于停止调用JNI函数的Java线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆