打印本文 打印本文  关闭窗口 关闭窗口  
信号量Semaphore实现互斥锁Mutex
作者:佚名  文章来源:不详  点击数  更新时间:2008/4/18 14:41:54  文章录入:杜斌  责任编辑:杜斌

  在Doug lea的那本著名的《Java并发编程—设计原则与模式》,英文名" Concurrent Programming in Java™: Design Principles and Patterns, Second Edition",书中提到可以用信号量Semaphore实现互斥锁Mutex。虽然java中是通过synchronize关键字提供锁,并用这个基础设施实现信号量的。在有的系统中只有信号量这一原语,锁是通过信号量实现的。代码如下:

import java.util.concurrent.Semaphore;

public class Mutex ...{
     private Semaphore s = new Semaphore(1);

     public void acquire() throws InterruptedException ...{
      s.acquire();
     }
    public void release()...{
      s.release();
     }
    public boolean attempt(int ms) throws InterruptedException ...{
      return s.tryAcquire(ms);
     }
}

  上面的代码只能在java5中编译通过,因为Semaphore是在java5中才提供的。我在读上面的代码时有疑问。因为如果错误的连续调用release两次,然后两个线程都调用acquire,岂不是这两个线程都可以同时运行,从而违背了互斥锁的定义?为了证明我的猜测,写了如下的代码:

public class TestMutex ...{
    public static void main(String[] args) throws InterruptedException...{
        Mutex mutex=new Mutex();
        mutex.acquire();
        mutex.release();
        mutex.release();
        new MyThread(mutex).start();
        new MyThread(mutex).start();
    }

}

class MyThread extends Thread...{
    private Mutex mutex;

    public MyThread(Mutex mutex) ...{
        this.mutex=mutex;
    }

    public void run()...{
        try ...{
            mutex.acquire();
        } catch (InterruptedException e1) ...{
            throw new RuntimeException(e1);
        }
        for(int i=0;i<10;i++)...{
            System.out.print(i);
            if(i%3==0)...{
                try ...{
                    Thread.sleep(100);
                } catch (InterruptedException e) ...{
                    e.printStackTrace();
                }
            }
        }
        mutex.release();
    }

该程序的输出如下:
00123123456456789789
从而证实了我的猜测。

打印本文 打印本文  关闭窗口 关闭窗口