同步代码依赖于简单的可重入锁,这种锁易于使用,但有许多限制,java.util.concurrent.locks包支持更复杂的锁定语法,咱们不会详细检查这个包,而是将重点放在其最基本的接口Lock上。html
Lock
对象的工做方式与同步代码使用的隐式锁定很是类似,与隐式锁同样,一次只有一个线程能够拥有一个Lock
对象,Lock
对象还经过其关联的Condition对象支持wait
/notify
机制。java
Lock
对象优于隐式锁的最大优势是它们可以退出获取锁的尝试,若是锁当即不可用或超时到期以前(若是指定),则tryLock
方法退出,若是另外一个线程在锁被得到以前发送中断,则lockInterruptibly
方法将退出。git
让咱们使用Lock
对象来解决咱们在活性中看到的死锁问题,Alphonse和Gaston训练本身注意朋友何时要鞠躬。咱们经过要求咱们的Friend
对象必须在继续执行bow
以前获取两个参与者的锁来对此进行建模,如下是改进模型Safelock的源代码。为了演示这个语法的多功能性,咱们假设Alphonse和Gaston如此迷恋他们新发现的安全鞠躬能力,他们不能中止相互鞠躬:github
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.Random; public class Safelock { static class Friend { private final String name; private final Lock lock = new ReentrantLock(); public Friend(String name) { this.name = name; } public String getName() { return this.name; } public boolean impendingBow(Friend bower) { Boolean myLock = false; Boolean yourLock = false; try { myLock = lock.tryLock(); yourLock = bower.lock.tryLock(); } finally { if (! (myLock && yourLock)) { if (myLock) { lock.unlock(); } if (yourLock) { bower.lock.unlock(); } } } return myLock && yourLock; } public void bow(Friend bower) { if (impendingBow(bower)) { try { System.out.format("%s: %s has" + " bowed to me!%n", this.name, bower.getName()); bower.bowBack(this); } finally { lock.unlock(); bower.lock.unlock(); } } else { System.out.format("%s: %s started" + " to bow to me, but saw that" + " I was already bowing to" + " him.%n", this.name, bower.getName()); } } public void bowBack(Friend bower) { System.out.format("%s: %s has" + " bowed back to me!%n", this.name, bower.getName()); } } static class BowLoop implements Runnable { private Friend bower; private Friend bowee; public BowLoop(Friend bower, Friend bowee) { this.bower = bower; this.bowee = bowee; } public void run() { Random random = new Random(); for (;;) { try { Thread.sleep(random.nextInt(10)); } catch (InterruptedException e) {} bowee.bow(bower); } } } public static void main(String[] args) { final Friend alphonse = new Friend("Alphonse"); final Friend gaston = new Friend("Gaston"); new Thread(new BowLoop(alphonse, gaston)).start(); new Thread(new BowLoop(gaston, alphonse)).start(); } }