【发布时间】: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