[英]ReentrantLock - unlock() method doesn't seem to work with lists
我正在编写一个程序,该程序必须以两种方式修改列表。 尽管此实现工作完美,但是它无法让第二个线程获得锁:
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;
}
也许有人知道为什么?
有些代码分支将永远不允许调用解锁。 例如在添加
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.