Mutex是互斥體
public interface Sync
{
public void acquire() throws InterruptedException;
//獲取許可
public boolean attempt(long msecs) throws InterruptedException;
//嘗試獲取許可
public void release();
//釋放許可
}
通過使用Sync可以替代Java synchronized關鍵字
注意Sync中的acquire()和attempt()都會拋出InterruptedException
class X
{
Sync gate; //
public void m()
{
try
{
gate
// block until condition holds
try
{
//
}
finally { gate
}
catch (InterruptedException ex) { //
}
}
Mutex是一個非重入的互斥鎖
public class Mutex implements Sync
{
/** The lock status **/
protected boolean inuse_ = false;
public void acquire() throws InterruptedException
{
if (Thread
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 (Thread
synchronized(this)
{
if (!inuse_)
{
inuse_ = true;
return true;
}
else if (msecs <=
return false;
else
{
long waitTime = msecs;
long start = System
try
{
for (;;)
{
wait(waitTime);
if (!inuse_)
{
inuse_ = true;
return true;
}
else
{
waitTime = msecs
if (waitTime <=
return false;
}
}
}
catch (InterruptedException ex)
{
notify();
throw ex;
}
}
}
}
}
為什麼要在acquire()和attempt(
release()方法簡單地重置inuse_標志
attempt()方法是利用Java的Object
Mutex是Sync的一個基本實現
class Node
{
Object item; Node next;
Mutex lock = new Mutex();
// 每一個節點都持有一個鎖
Node(Object x
{
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;
// (這兒可以更加緊湊
p
// Prime loop by acquiring first lock
// (If the acquire fails due to
// interrupt
// InterruptedException now
// so there is no need for any
// further cleanup
for (;;)
{
if (x
{
p
// 釋放當前節點的鎖
return true;
}
else
{
Node nextp = p
if (nextp == null)
{
p
// 釋放最後持有的鎖
return false;
}
else
{
try
{
nextp
// 在釋放當前鎖之前獲取下一個節點的鎖
}
catch (InterruptedException ex)
{
p
// 如果獲取失敗
}
p
// 釋放上個節點的鎖
p = nextp;
}
}
}
}
synchronized void add(Object x)
{
// 使用synchronized保護head域
head = new Node(x
}
//
}
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27377.html