14.2.5 示例:阀门类
在第5章的TestHarness中使用的“开始阀门闭锁”在初始化时指定的参数为1,从而创建了一个二元闭锁:它只有两种状态,即初始状态和结束状态。闭锁能阻止线程通过开始阀门,并直到阀门被打开,此时所有的线程都可以通过该阀门。虽然闭锁机制通常都能满足需求,但在某些情况下存在一个缺陷:按照这种方式构造的阀门在打开后无法重新关闭。
通过使用条件等待,可以很容易地开发一个可重新关闭的ThreadGate类,如程序清单14-9所示。ThreadGate可以打开和关闭阀门,并提供一个await方法,该方法能一直阻塞直到阀门被打开。在open方法中使用了notifyAll,这是因为这个类的语义不满足单次通知的“单进单出”测试。
程序清单14-9 使用wait和notifyAll来实现可重新关闭的阀门
@ThreadSafe
public class ThreadGate{
//条件谓词:opened-since(n)(isOpen||generation>n)
@GuardedBy("this")private boolean isOpen;
@GuardedBy("this")private int generation;
public synchronized void close(){
isOpen=false;
}
public synchronized void open(){
++generation;
isOpen=true;
notifyAll();
}
//阻塞并直到:opened-since(generation on entry)
public synchronized void await()throws InterruptedException{ ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access