先看一下stackoverflow上是怎么说的吧html
原文地址:http://stackoverflow.com/questions/771347/what-is-mutex-and-semaphore-in-java-what-is-the-main-differencejava
Semaphore can be counted, while mutex can only count to 1. Suppose you have a thread running which accepts client connections. This thread can handle 10 clients simultaneously. Then each new client sets the semaphore until it reaches 10.
When the Semaphore has 10 flags, then your thread won't accept new connections Mutex are usually used for guarding stuff. Suppose your 10 clients can access multiple parts of the system. Then you can protect a part of the system with a mutex so when 1 client is connected to that sub-system,
no one else should have access. You can use a Semaphore for this purpose too. A mutex is a "Mutual Exclusion Semaphore".
简单的说 就是Mutex是排它的,只有一个能够获取到资源, Semaphore也具备排它性,但能够定义多个能够获取的资源的对象。ui
1.Semaphorethis
Semaphore维护了一组许可令牌,使用acquire方法去获取许可令牌,而使用release方法去释放一个令牌。实际上没有真正的使用许可令牌,Semaphore仅仅维护了可用的计数器而已。spa
Semaphore一般用来限制可用访问一些(物理或者逻辑)资源的访问线程数。例如,下面的类使用Semaphore来控制对pool内item的访问量。.net
示例:线程
class Pool { private static final int MAX_AVAILABLE = 100; private final Semaphore available = new Semaphore(MAX_AVAILABLE, true); public Object getItem() throws InterruptedException { available.acquire(); return getNextAvailableItem(); } public void putItem(Object x) { if (markAsUnused(x)) available.release(); } // Not a particularly efficient data structure; just for demo protected Object[] items = ... whatever kinds of items being managed protected boolean[] used = new boolean[MAX_AVAILABLE]; protected synchronized Object getNextAvailableItem() { for (int i = 0; i < MAX_AVAILABLE; ++i) { if (!used[i]) { used[i] = true; return items[i]; } } return null; // not reached } protected synchronized boolean markAsUnused(Object item) { for (int i = 0; i < MAX_AVAILABLE; ++i) { if (item == items[i]) { if (used[i]) { used[i] = false; return true; } else return false; } } return false; } }
在访问池内的item时,每一个线程必须从Semaphore来获取一个许可令牌,保证必须有一个item是可用的。当线程使用完item后,将item还回到pool中,此时访问令牌返回给Semaphore。code
注意:当调用acquire方法是没有保持一个同步锁,由于同步锁会阻碍item被释放给pool。Semaphore封装了须要的同步操做来保证对pool的访问进行限制,而不是为了维持pool自己的一致性来加入同步操做。htm
Semaphore默认设置为1,用来保证至少有一个许可令牌可用,此时可用看作一个mutext排它锁。mutex因做为二分Semaphore而出名,要么有一个许可令牌,要么没有许可令牌。当这样使用时,二分Semaphore有熟悉(不像大部分lock的实现那样),lock由线程释放而非owner(Semaphore没有ownership的概念)。这在某些特殊的场景下颇有用,好比死锁的恢复。对象
Semaphore类的构造方法能够接受一个fairness参数,当这个参数设置为false时,此类不保证线程获取到许可令牌的顺序,特别是当运行抢夺资源时,意味着一个线程使用acquire获取许可令牌的时间可能会比一个等待队列在它以前的线程获取到令牌更早--逻辑上来讲,新线程放置月等待队列的头部。当fairness参数设置为true时,Semaphore保证线程调用acquire方法时的顺序获取到令牌(即先进先出FIFO)
参考文献:
【1】http://www.cnblogs.com/think-in-java/p/5520462.html
【2】http://blog.csdn.net/sunp823/article/details/49886051
【3】http://coolxing.iteye.com/blog/1236909