Google Guava项目是每个Java开发人员都应该熟悉的库的集合。 Guava库涵盖I / O,集合,字符串操作和并发性。 在这篇文章中,我将介绍Monitor类。 Monitor是一种同步构造,可以在使用ReentrantLock的任何地方使用。 在任何时候,只有一个线程可以占用一个监视器。 Monitor类具有进入和离开操作,这些操作在语义上与ReentrantLock中的锁定和解锁操作相同。 此外,监视器支持在布尔条件下等待。
比较Monitor和ReentrantLock
对于初学者,将Monitor和ReentrantLock进行并排比较会很有帮助。
public class ReentrantLockSample {
private List<String> list = new ArrayList<String>();
private static final int MAX_SIZE = 10;
private ReentrantLock rLock = new ReentrantLock();
private Condition listAtCapacity = rLock.newCondition();
public void addToList(String item) throws InterruptedException {
rLock.lock();