Mutex是一个非重入的互斥锁Mutex广泛地用在需要跨越方法的before/after类型的同步环境中下面是Doug Lea的concurrent工具包中的Mutex的实现
public class Mutex implements Sync
{
/** The lock status **/
protected boolean inuse_ = false;
public void acquire() throws InterruptedException
{
if (Threadinterrupted()) throw new InterruptedException();//()
synchronized(this)
{
try
{
while (inuse_) wait();
inuse_ = true;
}
catch (InterruptedException ex)
{
//()
notify();
throw ex;
}
}
}
public synchronized void release()
{
inuse_ = false;
notify();
}
public boolean attempt(long msecs) throws InterruptedException
{
if (Threadinterrupted()) throw new InterruptedException();
synchronized(this)
{
if (!inuse_)
{
inuse_ = true;
return true;
}
else if (msecs <= )
return false;
else
{
long waitTime = msecs;
long start = SystemcurrentTimeMillis();
try
{
for (;;)
{
wait(waitTime);
if (!inuse_)
{
inuse_ = true;
return true;
}
else
{
waitTime = msecs (SystemcurrentTimeMillis() start);
if (waitTime <= ) // ()
return false;
}
}
}
catch (InterruptedException ex)
{
notify();
throw ex;
}
}
}
}
}
[] [] []