熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java高級技術 >> 正文

Java多線程同步設計中使用Metux[2]

2013-11-23 19:55:29  來源: Java高級技術 

    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;
    }
   }
  }
 }
}

[]  []  []  


From:http://tw.wingwit.com/Article/program/Java/gj/201311/27680.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.