import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class Foo {
private ReentrantLock _lock;
private Condition _cond;
private Thread _thr;
private LinkedList<String> _msgQueue;
public Foo() {
_lock = new ReentrantLock();
_cond = _lock.newCondition();
_msgQueue = new LinkedList<String>();
startThread();
}
public void putMsg(String msg) throws Exception {
_lock.lock();
_msgQueue.addLast(msg);
_cond.signal();
System.out.println(Thread.currentThread().getId() + ": Signal write thread.");
_lock.unlock();
System.out.println(Thread.currentThread().getId() + ": Unlocked.");
}
private void startThread() {
_thr = new Thread() {
public void run() {
_lock.lock();
while(true) {
try {
while (!_msgQueue.isEmpty()) {
String msg = _msgQueue.getFirst();
System.out.println(msg);
_msgQueue.removeFirst();
}
System.out.println(Thread.currentThread().getId() + ": getHoldCount:" + _lock.getHoldCount());
System.out.println((Thread.currentThread().getId() + ": isLocked:" + _lock.isLocked()));
System.out.println(Thread.currentThread().getId() + ": isHeldByCurrentThread:" + _lock.isHeldByCurrentThread());
System.out.println(Thread.currentThread().getId() + ": Awaiting...");
_cond.await();
System.out.println(Thread.currentThread().getId() + ": Write thread awaken");
} catch (Exception e) {
e.printStackTrace();
break;
} finally {
try {
_lock.unlock();
} catch (Exception e) {
}
}
}
System.out.println("Write thread exit.");
}
};
_thr.start();
}
}
public class LockTest {
public static void main(String[] args) throws Exception {
Foo foo = new Foo();
foo.putMsg("Msg 1");
foo.putMsg("Msg 2");
Thread.sleep(1000);
foo.putMsg("Msg 3");
}
}
一次运行后的代码输出: 1:信号写入线程。 1:解锁。 1:信号写入线程。 1:解锁。 消息 1 消息 2 8:getHoldCount:1 8: isLocked:true 8: isHeldByCurrentThread:true 8:等待... 1:信号写入线程。 1:解锁。 8:写线程唤醒 消息 3 8:getHoldCount:0 8:被锁定:假 8: isHeldByCurrentThread:false 8:等待... 写线程退出。 java.lang.IllegalMonitorStateException 在 java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(Unknown Source) at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(Unknown Source) at java.util.concurrent.locks.AbstractQueuedSynchronizer.fullyRelease(Unknown Source) at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(未知来源) 在 Foo$1.run(LockTest.java:44)
问题是:根据http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Condition.html#await(),当线程返回时,它保证握住这把锁。但是从输出中,我们看到 await() 返回后,并没有重新获取锁。这是一个错误还是我犯了一些错误?