设为首页 加入收藏

TOP

信号量Semaphore实现互斥锁Mutex
2014-11-15 21:00:36 来源: 作者: 【 】 浏览:23
Tags:信号 Semaphore 实现 Mutex

  在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
从而证实了我的猜测。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇JSP页面中连接IBMCloudscape(der.. 下一篇根据输入的长度动态的截取字符串..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: