日期:2014-05-20  浏览次数:20652 次

java高人请进,帮忙分析下,进程deadlock问题
第一块:
{....
synchronized(queue)   {
if   (isEmpty()   )  
{
misServer.getLog().debug( "Getting   in   wait   status! ");
queue.wait();
misServer.getLog().debug( "   ...   Awakened! ");
.....
}
}
...go   on  
}
//上边是某个方法调用的queue等待,判断如果queue为空,则等待,否则执行...

第二块:

public   void   insert(BIT   bit)   {
misServer.getLog().debug( "Inserting   BIT   Record   ... ");
if   (queue.getTotalElements()   <   maxQueueSize)   {
queue.insert(bit);
//   The   insert   method   in   FifoQueue   will   notify   the   thread(s)   in   wait   status
}   else   {
misServer.getLog().warn( "Queue   is   full,   unable   to   add   BIT:   "   +   bit);
}}
//上边是向queue中插入数据

第三块:
public   synchronized   void   insert(Object   object)   {

//   Initialize   the   new   element
DoubleLinkedElement   element   =   new   DoubleLinkedElement();
element.object   =   object;

if   (head   ==   null)   {
//   Add   first   element   in   the   queue.
element.next   =   null;
element.prev   =   null;
head   =   element;
tail   =   element;
}   else   {
//   Add   element   to   the   others   in   the   queue.
element.next   =   head;
head.prev   =   element;
head   =   element;
}   //   end   if

totalElements++;

lastInsertTime.now();
this.notify();
}
//上边是insert方法实现

现象:发生deadlock,第一部分无法执行go   on   部分
我的分析:
第三部分中,唤醒是否执行

请教高人,是否有其他原因,请说明理由。最好能编写小工具测试

------解决方案--------------------
this.notify()改成this.notifyAll()
notify()会任意选择一个在等待中的线程,但不一定是你想要唤醒的线程
------解决方案--------------------
这个应该符合生产者/消费者模型,注意3个地方:1,队列满的时候生产者阻塞 2,队列空的时候消费者阻塞 3 生产者和消费者互斥访问,避免竞争。
------解决方案--------------------
要实现同步必需有一个共同的同步化的对象:

queue.wait(); 中的queue和this.notify();中的this是同一个对象吗?