为什么要在acquire()和attempt(方法的开始都要检查当前线程的中断标志呢?这是为了在当前线程已经被打断时可以立即返回而不会仍然在锁标志上等待调用一个线程的interrupt()方法根据当前线程所处的状态可能产生两种不同的结果当线程在运行过程中被打断则设置当前线程的中断标志为true;如果当前线程阻塞于wait()sleep()join()则当前线程的中断标志被清空同时抛出InterruptedException所以在上面代码的位置()也捕获了InterruptedException然后再次抛出InterruptedException
release()方法简单地重置inuse_标志并通知其它线程
attempt()方法是利用Java的Objectwait(long)进行计时的由于Objectwait(long)不是一个精确的时钟所以attempt(long)方法也是一个粗略的计时注意代码中位置()在超时时返回
Mutex是Sync的一个基本实现除了实现了Sync接口中的方法外并没有添加新的方法所以Mutex的使用和Sync的完全一样在concurrent包的API中Doug给出了一个精细锁定的List的实现示例我们这儿也给出作为对Mutex和Sync使用的一个例子
class Node
{
Object item; Node next;
Mutex lock = new Mutex();
// 每一个节点都持有一个锁
Node(Object x Node n)
{
item = x;
next = n;
}
}
class List
{
protected Node head;
// 指向列表的头
// 使用Java的synchronized保护head域
// (我们当然可以使用Mutex但是这儿似乎没有这样做的必要
protected synchronized Node getHead()
{ return head; }
boolean search(Object x) throws InterruptedException
{
Node p = getHead();
if (p == null) return false;
// (这儿可以更加紧凑但是为了演示的清楚各种情况都分别进行处理)
plockacquire();
// Prime loop by acquiring first lock
// (If the acquire fails due to
// interrupt the method will throw
// InterruptedException now
// so there is no need for any
// further cleanup)
for (;;)
{
if (xequals(pitem))
{
plockrelease();
// 释放当前节点的锁
return true;
}
else
{
Node nextp = pnext;
if (nextp == null)
{
plockrelease();
// 释放最后持有的锁
return false;
}
else
{
try
{
nextplockacquire();
// 在释放当前锁之前获取下一个节点的锁
}
catch (InterruptedException ex)
{
plockrelease();
// 如果获取失败也释放当前的锁 throw ex;
}
plockrelease();
// 释放上个节点的锁现在已经持有新的锁了
p = nextp;
}
}
}
}
synchronized void add(Object x)
{
// 使用synchronized保护head域
head = new Node(x head);
}
// other similar traversal and update methods
}
[] [] []