java

位置:IT落伍者 >> java >> 浏览文章

Java多线程同步设计中使用Metux[2]


发布日期:2021年08月21日
 
Java多线程同步设计中使用Metux[2]

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;

}

}

}

}

}

[] [] []

               

上一篇:Java多线程同步设计中使用Metux[3]

下一篇:Java多线程同步设计中使用Metux[1]