Java多线程同步设计中使用Metux
http://tech.ddvip.com 2006年11月25日 社区交流
本文详细介绍Java多线程同步设计中使用Metux
class X
{
Sync gate; // ...
public void m()
{
try
{
gate.acquire();
// block until condition holds
try
{
// ... method body
}
finally { gate.release(); }
}
catch (InterruptedException ex) { // ... evasive action }
}
}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 (Thread.interrupted()) throw new InterruptedException();//(1)
synchronized(this)
{
try
{
while (inuse_) wait();
inuse_ = true;
}
catch (InterruptedException ex)
{
//(2)
notify();
throw ex;
}
}
}
public synchronized void release()
{
inuse_ = false;
notify();
}
public boolean attempt(long msecs) throws InterruptedException
{
if (Thread.interrupted()) throw new InterruptedException();
synchronized(this)
{
if (!inuse_)
{
inuse_ = true;
return true;
}
else if (msecs <= 0)
return false;
else
{
long waitTime = msecs;
long start = System.currentTimeMillis();
try
{
for (;;)
{
wait(waitTime);
if (!inuse_)
{
inuse_ = true;
return true;
}
else
{
waitTime = msecs - (System.currentTimeMillis() - start);
if (waitTime <= 0) // (3)
return false;
}
}
}
catch (InterruptedException ex)
{
notify();
throw ex;
}
}
}
}
}为什么要在acquire()和attempt(0方法的开始都要检查当前线程的中断标志呢?这是为了在当前线程已经被打断时,可以立即返回,而不会仍然在锁标志上等待。调用一个线程的interrupt()方法根据当前线程所处的状态,可能产生两种不同的结果:当线程在运行过程中被打断,则设置当前线程的中断标志为true;如果当前线程阻塞于wait()、sleep()、join(),则当前线程的中断标志被清空,同时抛出InterruptedException。所以在上面代码的位置(2)也捕获了InterruptedException,然后再次抛出InterruptedException。
责编:豆豆技术应用
正在加载评论...