두 개의 스레드가 있으며 현재 동기화 된 블록 내에서 개체의 notify() 및 wait() 메서드를 사용하여 잠금을 수행하고 있습니다. 나는 메인 스레드가 너무 차단되지 않습니다 나는이 방법 부울 사용 있는지 확인하고 싶었 (에만 관련 코드를 제공합니다.)동기화 된 블록 및 잠금
//Just to explain an example queue
private Queue<CustomClass> queue = new Queue();
//this is the BOOLEAN
private boolean isRunning = false;
private Object lock;
public void doTask(){
ExecutorService service = Executors.newCachedThreadPool();
//the invocation of the second thread!!
service.execute(new Runnable() {
@Override
public void run() {
while(true){
if (queue.isEmpty()){
synchronized (lock){
isRunning = false; //usage of boolean
lock.wait();
}
}
else{
process(queue.remove());
}
}
});
}
//will be called from a single thread but multiple times.
public void addToQueue(CustomClass custObj){
queue.add(custObj);
//I don't want blocking here!!
if (!isRunning){
isRunning = true; //usage of BOOLEAN!
synchronized(lock){
lock.notify();
}
}
}
가 일이 잘못 여기 보인다합니까? 감사. 편집 : 목적 : add()가 두 번째 이상 호출 될 때이 방법은 notify()에서 차단되지 않습니다. 주 스레드의 비 차단 동작을 달성하는 더 좋은 방법이 있습니까?
흠, BlockingQueue '? – fge
'isRunning'을'volatile '으로 표시하면 두 스레드에서 액세스 할 수 있습니다 –
무엇이 문제입니까? –