我有两个线程,我目前正在使用同步块内的对象的 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() 上被阻塞。有没有更好的方法来实现主线程的这种非阻塞行为?