Art Java concurrent programming (16) Semaphore

Semaphore control the number of concurrent threads

Semaphore (Semaphore) is used to control the number of threads simultaneously access a particular resource, which through the coordination of the various threads, in order to ensure rational use of public resources

For example, to limit ×× road traffic, allowing only a hundred vehicles while exercising in this way, others must wait in the intersection, so the first one hundred cars will see the green, which entered this road, behind the car will see a red light, not ×× into the street, but if the first one hundred in five vehicles have left the road ××, then the latter will allow five cars into the road, this case said car is the thread into the thread in the implementation of the road it means, it means leaving the road thread execution is completed, saw the red light indicates that the thread is blocked, it can not be executed.

Scenarios

Semaphore can be used to do traffic control, in particular, with limited public resources application scenarios, such as database connection. If there is a need to read tens of thousands of data files, as are the IO-intensive tasks, we can start to read dozens of concurrent threads, but if read into memory, also need to be stored in the database, and the number of connections to the database only 10, then we have to control only 10 threads simultaneously save the database connection data, otherwise it will error unable to get database connection. This time, you can use Semaphore to do traffic control

public class SemaphoreTest {
    private static final int THREAD_COUNT = 30;    30个线程在执行
    private static Executor ServicethreadPool =Executors.newFixedThreadPool(THREAD_COUNT);
    private static Semaphore s = new Semaphore(10);     只允许10个并发执行

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        s.acquire();
                        System.out.println("save data");
                        s.release();
                    } catch (InterruptedException e) {
                    }
                }
            });
        }
        threadPool.shutdown();
    }
}

Semaphore usage is also very simple, first of all threads of Semaphore acquire () method to get a license, call the release () method to return the license after use. You can also use tryAcquire () method attempts to obtain a license.

Other methods

Semaphore provides other methods, as follows.
· IntavailablePermits (): Returns the number of licenses in this semaphore currently available.
· IntgetQueueLength (): Returns the number of threads that are waiting to obtain a license.
· BooleanhasQueuedThreads (): whether any threads are waiting to acquire a license.
· Void reducePermits (int reduction): to reduce the reduction licenses, is a protected method.
· Collection getQueuedThreads (): Returns the collection of all the threads waiting to acquire a license, is a protected method.

Published 24 original articles · won praise 1 · views 535

Guess you like

Origin blog.csdn.net/qq_45366515/article/details/105267066