1

我正在编写一个必须以两种方式修改列表的程序。尽管此实现完美运行,但它无法让第二个线程获取锁:

Node head = new Node(new Object(), null);
public static ReentrantLock lock = new ReentrantLock();
...

boolean add(Object o){
    lock.lock();
    Node current = head;
    Node previous = head.next;

    if(head.next==null){
        head.addNext(new Node(o,null));
        return true;
    }
    while(!(current.next == null)){
        current=current.next;
        previous=previous.next;
    }
    current.addNext(new Node(o,null));
    lock.unlock();
    return true;    
}

也许有人知道这是为什么?

4

1 回答 1

7

有些代码分支永远不允许调用解锁。例如在添加

if(head.next==null){
    head.addNext(new Node(o,null));
    return true;
}

您无需解锁即可返回。您应该遵循lock try finally unlock语义。

lock.lock();
try{
   ... do stuff 
   return true;
}finally{
   lock.unlock();
} 
于 2013-11-01T21:05:12.810 回答