在我的应用程序中,我有一些本机代码的包装器,它通过JNI桥调用.此本机代码需要在单独的线程中执行(并行处理).但问题是代码有时会"挂起",因此线程需要"强制"终止.不幸的是我没有找到任何"微妙"的方法:一般建议是告诉线程中的代码优雅地退出,但我不能用这个本机代码(这是上面的第三方代码).
我使用Java Concurrent API进行任务提交:
Future<Integer> processFuture = taskExecutor.submit(callable);
try {
result = processFuture.get(this.executionTimeout, TimeUnit.SECONDS).intValue();
}
catch (TimeoutException e) {
// How to kill the thread here?
throw new ExecutionTimeoutException("Execution timed out (max " + this.executionTimeout / 60 + "min)");
}
catch (...) {
... exception handling for other cases
}
Run Code Online (Sandbox Code Playgroud)
Future#cancel()只会中断线程,但不会终止它.所以我使用了以下技巧:
class DestroyableCallable implements Callable<Integer> {
private Thread workerThread;
@Override
public Integer call() {
workerThread = Thread.currentThread();
return Integer.valueOf(JniBridge.process(...));
}
public void stopWorkerThread() {
if (workerThread != null) { …Run Code Online (Sandbox Code Playgroud)