从Java线程调用C函数后,整个Java应用程序变得无响应 [英] whole Java application becomes unresponsive after C function call from Java thread

查看:111
本文介绍了从Java线程调用C函数后,整个Java应用程序变得无响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了这种Android Java类,其中本机函数baresipStart()永不终止:

I have defined this kind of Android Java class, where native function baresipStart() never terminates:

package com.tutpro.baresip;

public class BaresipThread extends Thread {

    public void start() {
        baresipStart();
    }

    public void kill() {
        baresipStop();
    }

    public native void baresipStart();
    public native void baresipStop();

}

然后我从另一个Java类调用其start()函数:

I then call its start() function from another Java class:

BaresipThread thread;
thread = new BaresipThread();
thread.start();

结果是baresipStart()函数开始正常运行,但是应用程序的其余部分变得完全无响应.

The result is that baresipStart() function starts to run fine, but rest of the application becomes completely unresponsive.

这是为什么以及如何修复代码,以使baresipStart()函数在后台运行而不停止所有其他活动?

Why is that and how to fix the code so that baresipStart() function runs in the background without stopping all other activity?

推荐答案

Thread.start()负责实际创建新的执行线程并将其设置为运行.通过像您那样覆盖它,使它改为在调用start() 的线程中运行baresipStart().

Thread.start() is responsible for actually creating the new thread of execution and setting it running. By overriding it as you did, you cause it to instead run baresipStart(), in the thread that invokes start().

您应该覆盖run(),而不是覆盖start().该方法定义了在新的执行线程中要执行的工作.

Instead of overriding start(), you should override run(). This method is what defines the work to be performed in the new thread of execution.

此外,如果本机方法baresipStart()确实从不返回,那么您就遇到了问题.您的应用程序具有任何活动线程时,无法终止.假设您打算让baresipStop()导致线程完成,那么当通过调用baresipStop()终止执行时,应该安排baresipStart()返回(或引发未检查的异常).但是请注意,这些本机方法必须是线程安全的,因为它们将被不同的Java线程强制执行.

Furthermore, if native method baresipStart() indeed never returns then you have a problem. Your application cannot terminate while it has any active threads. Supposing that you intend for baresipStop() to cause the thread to finish, you should arrange for baresipStart() to return (or to throw an unchecked exception) when execution is terminated by an invocation of baresipStop(). Do be aware, however, that those native methods need to be thread-safe, because they will, perforce, be invoked by different Java threads.

这篇关于从Java线程调用C函数后,整个Java应用程序变得无响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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