Java Multithreading - New Feature - Semaphore Semaphore

Introduction
Semaphore, sometimes called semaphore, is a facility used in a multi-threaded environment, which is responsible for coordinating various threads to ensure that they can use common resources correctly and reasonably.

The concept
Semaphore is divided into two types: single-valued and multi-valued, the former can only be obtained by one thread, and the latter can be obtained by several threads.

Take the operation of a parking lot as an example. For simplicity, let's say the parking lot has only three spaces, and all three spaces are empty at first. At this time, if five cars come at the same time, the gatekeeper allows three of them to enter unobstructed, and then puts down the car block, and the rest of the cars must wait at the entrance, and all subsequent cars have to wait at the entrance. At this time, a car leaves the parking lot. After the gatekeeper finds out, he opens the car stop and puts in one car. If two cars leave, he can put in two more cars, and so on.

In this parking lot system, parking spaces are public resources, each car is like a thread, and the gatekeeper acts as a semaphore.

Further, the characteristics of a semaphore are as follows: a semaphore is a non-negative integer (number of cars), and all threads (vehicles) passing through it will decrement the integer by one (passing it to use resources, of course), when the integer value is At zero, all threads trying to pass it will be in a wait state. We define two operations on the semaphore: Wait (wait) and Release (release). When a thread calls the Wait operation, it either goes through and decrements the semaphore by one, or waits until the semaphore is greater than one or times out. Release is actually an add operation on the semaphore, corresponding to the vehicle leaving the parking lot, the operation is called "release" because the add operation actually releases the resource guarded by the semaphore.

In java, you can also set whether the semaphore adopts fair mode. If it is executed in a fair way, the threads will be executed in the order of arrival (FIFO). If it is not fair, the later requests may be queued at the head of the queue. Department.
Defined in the JDK as follows:
Semaphore(int permits, boolean fair)
  Creates a Semaphore with the given number of permits and the given fairness settings.

Semaphore is currently being extended and used in a multi-threaded environment. The semaphore of the operating system is a very important concept and has applications in process control. The Java concurrency library Semaphore can easily complete semaphore control. Semaphore can control the number of resources that can be accessed at the same time, obtain a license through acquire(), wait if not, and release() release a license. For example, under Windows, you can set the maximum number of client accesses to shared files.

The function implemented by Semaphore is similar to that there are 5 pits in the toilet. If 10 people want to go to the toilet, how many people can only go to the toilet at the same time? Only 5 people can occupy it at the same time. When any one of the 5 people gets out of the way, one of the other 5 people who are waiting can occupy it. In addition, the 5 people waiting can get the priority chance randomly, or they can get the chance in the order of first come, first come, depending on the parameter options passed in when constructing the Semaphore object. The Semaphore object of a single semaphore can implement the function of a mutex, and one thread can acquire the "lock" and then release the "lock" by another thread, which can be used in some cases of deadlock recovery.

 

copy code
package cn.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * signal
 *
 * @author Lin Jiqin
 * @version 1.0 2013-7-25 02:03:40 PM
  */ 
public  class SemaphoreTest {
     public  static  void main(String[] args) {
         // Thread pool 
        ExecutorService exec = Executors.newCachedThreadPool();
         // only 5 Threads access 
        final Semaphore at the same time semp = new Semaphore(5 );
         // Simulate 20 client accesses 
        for ( int index = 0; index < 50; index++ ) {
             final  int NO = index;
            Runnable run = new Runnable() {
                public void run() {
                    try {
                        // 获取许可
                        semp.acquire();
                        System.out.println("Accessing: " + NO);
                        Thread.sleep(( long ) (Math.random() * 10000 ));
                         // After accessing, release 
                        semp.release();
                         // availablePermits() refers to how many in the current semaphore library can be used 
                        System .out.println("-----------------" + semp.availablePermits());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            exec.execute(run);
        }
        // 退出线程池
        exec.shutdown();
    }
}
copy code
copy code
Accessing: 0
Accessing: 1
Accessing: 2
Accessing: 4
Accessing: 6
Accessing: 8
-----------------0
-----------------1
Accessing: 3
-----------------1
Accessing: 5
Accessing: 9
-----------------0
-----------------1
Accessing: 7
Accessing: 10
-----------------0
-----------------1
Accessing: 11
-----------------1
Accessing: 12
-----------------1
Accessing: 13
Accessing: 14
-----------------0
-----------------1
Accessing: 15
-----------------0
Accessing: 16
-----------------1
Accessing: 17
-----------------1
Accessing: 18
-----------------1
Accessing: 19
-----------------0
Accessing: 20
Accessing: 21
-----------------0
Accessing: 22
-----------------0
-----------------1
Accessing: 23
-----------------1
Accessing: 24
-----------------0
Accessing: 25
Accessing: 26
-----------------0
-----------------1
Accessing: 27
-----------------1
Accessing: 28
-----------------1
Accessing: 29
Accessing: 30
-----------------0
-----------------1
Accessing: 31
-----------------1
Accessing: 32
-----------------1
Accessing: 33
-----------------1
Accessing: 34
Accessing: 35
-----------------0
-----------------1
Accessing: 36
-----------------1
Accessing: 37
-----------------1
Accessing: 38
-----------------1
Accessing: 39
-----------------1
Accessing: 40
Accessing: 41
-----------------0
-----------------1
Accessing: 42
Accessing: 43
-----------------0
Accessing: 44
-----------------0
-----------------1
Accessing: 45
-----------------1
Accessing: 46
-----------------1
Accessing: 47
-----------------1
Accessing: 48
-----------------1
Accessing: 49
-----------------1
-----------------2
-----------------3
-----------------4
-----------------5
copy code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326257323&siteId=291194637