【问题标题】:Android Service and worker thread ReentrantLock infinite loopAndroid Service 和工作线程 ReentrantLock 无限循环
【发布时间】:2016-09-21 17:50:04
【问题描述】:

您好,我想摆脱在服务中持有工作线程的无限循环。

我尝试使用 ReentrantLock() 方法,但我似乎无法让它工作。

我的工作线程从 JNI 调用 nativeWaitForTask 方法并进入睡眠状态。

但我的服务主线程似乎无法在他应该向工作线程发出信号的 submitTask 方法中唤醒他。

这就像 await() 调用也阻塞了服务的主线程。

但据我所知,它们在不同的线程上......

我做错了什么?为什么它不起作用?

    private synchronized void nativeWaitForTask() {

    threadLock.lock();

    try {


        while(opcode == SR_Manager.STATE_IDLE) {

            newTask.await();
        }

    }catch (InterruptedException e) {

        e.printStackTrace();
        Log.e(SR_Manager.DEBUG_TAG,"Failed to wait for new task! " + e.toString());

    }finally {

        threadLock.unlock();
    }
}


    private synchronized void submitTask() {

    if (nativeMain.isAlive()) {

        dstImageName = sr.getDstImageName();

        if (sr.getSrcImagePath() != null && !sr.getSrcImagePath().equals(srcImagePath)) {

            srcImagePath = sr.getSrcImagePath();
            width = sr.getWidth();
            height = sr.getHeight();
            format = sr.getFormat();
            algorithm = sr.getAlgorithm();
            value = sr.getValue();
            saveOutput = sr.getSaveOutput();
            opcode = SR_Manager.STATE_LOAD_IMAGE;

        } else if (sr.getOpcode() != SR_Manager.STATE_LOAD_IMAGE) {

            algorithm = sr.getAlgorithm();
            value = sr.getValue();
            saveOutput = sr.getSaveOutput();
            opcode = sr.getOpcode();
        }

        t0 = System.currentTimeMillis();

    } else {

        // No native thread no service...
        silentCrash(-100);
    }

    // Wake the worker thread which waits for the new task condition
    threadLock.lock();
    newTask.signal();
    threadLock.unlock();
}

【问题讨论】:

    标签: android multithreading service java-native-interface reentrantlock


    【解决方案1】:

    错误是在方法中使用了同步关键字。它给工作线程一个双重锁,一个是锁对象,一个是服务实例(this)对象,并阻塞了服务的主线程。

    现在效果很好,并且在工作线程等待任务时将 CPU 使用率从无限循环的恒定 12% 降至 0%。

    【讨论】:

      猜你喜欢
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 1970-01-01
      • 2021-02-21
      相关资源
      最近更新 更多