当发生 JNI 代码错误时,如何正确停止线程?

How do I properly stop the thread when a JNI code error occurs?

我看过How to properly stop the Thread in Java?。 但是C里面没有try&catch。

我在线程中调用了一个 JNI 函数。我想在出现问题时停止线程。

error()中我应该怎么做才能防止代码隐藏和停止线程?

当我在函数1中调用error()时,如何避免后续函数执行?

我的代码是这样的:

new Thread() (new Runnable() {
        @Override
        public void run() {
            JNIfunction();
        }
    }).start();

JNI函数():

while(flag) {
    //Function1, call error() to stop thread when wrong.
    //Function2, call error() to stop thread when wrong.
    //Function3, call error() to stop thread when wrong.
    ...
}

错误():

void error() {
    flag= 0;
}

设置flag=0。会退出循环,线程自然结束。

使用boolean volatile变量跟踪错误情况,然后使用interrupt()停止线程。
类似问题回答的很详细How to properly stop the Thread in Java?