0
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() 返回后,并没有重新获取锁。这是一个错误还是我犯了一些错误?

4

1 回答 1

1

根据http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Condition.html#await(),当线程返回时,它保证持有这个锁。

没错,但它也说线程必须在调用方法之前持有锁:

调用此方法时,假定当前线程持有与此 Condition 关联的锁。由实现决定是否是这种情况,如果不是,如何响应。通常,将引发异常(例如 IllegalMonitorStateException),并且实现必须记录该事实。

这与“普通”监视器(Object#wait)的工作方式相同:您必须在开始等待时保持锁定(在 Object#wait 的情况下使用同步块,此处使用 Lock#lock)。然后锁将被释放,您等待。当等待结束时,你也再次持有锁。

于 2013-07-24T04:22:50.513 回答