In the previous article "Preliminary tutorial on multithreading synchronization -- design and use of Metux", we discussed the design and implementation of Mutux in Doug Lea's concurrent package, this article discusses the design and use of Simaphore, which is also common in multithreaded programming. Simaphore also inherits from the Sync interface. Compared with Mutex, Simaphore adds support for Synchronous counting. A Simaphore represents multiple licenses. You can obtain multiple licenses at a time or release multiple licenses at a time. If you reduce the number of Simaphore licenses to 1, it can be used as a Mutex. The following code demonstrates the basic usage of Simaphore:
- ClassPool {
- Static FinalMAX_AVAILABLE = 100;// 100 licenses
- Private FinalSemaphore available =NewSemaphore (MAX_AVAILABLE );
- Public ObjectGetItem ()Throws InterruptedException{// No synch
- Available. acquire ();
- ReturnGetNextAvailableItem ();
- }
-
- Public VoidPutItem (ObjectX ){// No synch
- If(MarkAsUnused (x ))
- Available. release ();
- }
-
- // Not a particle ly efficient data structure; just for demo
-
- Protected Object[] Items =... whatever kinds of items being managed
- Protected Boolean[] Used =New Boolean[MAX_AVAILABLE];
-
- Protected Synchronized ObjectGetNextAvailableItem (){
- For(IntI = 0; I <MAX_AVAILABLE; ++ I ){
- If(! Used [I]) {
- Used [I] =True;
- ReturnItems [I];
- }
- }
- Return Null;// Not reached
- }
-
- Protected Synchronized BooleanMarkAsUnused (ObjectItem ){
- For(IntI = 0; I <MAX_AVAILABLE; ++ I ){
- If(Item = items [I]) {
- If(Used [I]) {
- Used [I] =False;
- Return True;
- }
- Else
- Return False;
- }
- }
- Return False;
- }
-
- }
It can be seen that Simaphore is an enhancement of Mutex, and Simaphore is also compared with Mutex, the following method is added:
1. public Semaphore (long initialPermits)
Constructor to specify the number of licenses.
2. public synchronized long permits ()
The number of returned licenses.
3. public synchronized void release (long n)
Release n licenses at a time.
Correspondingly, in the implementation of Simaphore, a field is also added, the number of storage licenses:
Protected long permits _;
The acquire and release methods have also changed accordingly:
- /** Wait until a permit is available, and take one **/
- Public VoidAcquire ()Throws InterruptedException{
- If(Thread. Interrupted ())Throw New InterruptedException();
- Synchronized(This){
- Try{
- While(Permits _ <= 0) wait ();
- -- Permits _;
- }
- & Nb