Skip to Content
Java并发编程实战
book

Java并发编程实战

by Brian Goetz, Tim Peierls
August 2021
Beginner to intermediate
450 pages
5h 40m
Chinese
Pearson
Content preview from Java并发编程实战

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

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

数据驱动力:企业数据分析实战

数据驱动力:企业数据分析实战

Carl Anderson
Python机器学习案例精解

Python机器学习案例精解

Posts & Telecom Press, Yuxi (Hayden) Liu
RxJava反应式编程

RxJava反应式编程

Tomasz Nurkiewicz, Ben Christensen
软件开发实践:项目驱动式的Java开发指南

软件开发实践:项目驱动式的Java开发指南

Raoul-Gabriel Urma, Richard Warburton

Publisher Resources

ISBN: 9787111370048