notify() 및 wait()를 사용하려고합니다. 여기 내 원하는 수업이 있습니다. addNewItem()
으로 전화를 걸 때 문제가 있습니다. tryToReadItem()
을 먼저 호출 한 다음 addNewItem()
메서드를 호출하면 해당 로그가 인쇄되지 않습니다. 내 DemoClass
이 싱글 톤입니다. 내가 모르는 뭔가가Android notify() 메소드가 호출되지 않았습니다.
DemoClass executor = DemoClass.getInstance();
boolean bool = executor.addNewItem();
암 : 여기
public class DemoClass {
private static final String TAG = "DemoClass";
private static DemoClass instance;
private Object lock = new Object();
private static Thread executor;
private static Runnable reader;
static MyQueue queue;
private DemoClass() {
queue = MyQueue.getInstance();
reader = new Runnable() {
@Override
public void run() {
tryToReadRequest();
}
};
}
public static DemoClass getInstance() {
if (null == instance) {
instance = new RequestExecutor();
executor = new Thread(reader);
executor.run();
}
return instance;
}
public boolean addNewItem() {
synchronized (lock) {
lock.notify(); // executor will be run
Log.i(TAG, "executor run...");
}
return true;
}
public void tryToReadItem() {
try {
while (true) {
synchronized (lock) {
if (queue.checkTopValue() == null) {
Log.v(TAG, "queue is empty");
lock.wait();
} else {
//TODO other code...
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
해당 클래스의 사용인가?
편집 : 방금 코드를 변경했습니다. 이제 tryToReadRequest()
은 queue가 비어 있지 않은 동안 계속 실행됩니다. 하지만 내 문제는 라인 lock.notify();
이 실행되지 않는다는 것입니다.
모두 같은 스레드에 있습니다. 다른 스레드가 관련되어야합니다. – Enzokie
당신이 notifyAll에게 통보를 변경하면 같은 결과가있는 것 같군요, 맞습니까? – DEADMC
문제와 관련이 없지만 적절한 싱글 톤을 위해서는 getInstance() 및 e.printStackTrace()에서 synchronized 블록이 필요합니다. 안드로이드에서 작동하지 않는다면, 대신 Log.e ("tag", Log.getStackTraceString (e))를 써야만합니다. – DEADMC