[英]Android Service and worker thread ReentrantLock infinite loop
嗨,我想摆脱一个无限循环,该无限循环在服务中保存一个工作线程。
我尝试使用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();
}
错误是对方法使用了synced关键字。 它给工作线程提供了双重锁定,一个具有锁定对象,另一个具有服务实例(此)对象,并阻塞了服务的主线程。
这现在可以很好地运行,并且在工作线程等待任务时将CPU使用率从无限循环的恒定12%降至0%。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.