Java Multithreading semaphore use instances, granular control concurrent number of granularity

Source: Internet
Author: User

1, Semaphore: Thread Synergy class, used to control the number of concurrent threads, and can be more fine-grained to control, because the real control of the most concurrent code is placed between the acquire and release.

2, the main methods:

Semaphore semaphore = new semaphore (int count);

The initialization method for semaphore semaphore, in which the initial value count represents the current semaphore, the number of threads currently allowed concurrent access.

Semaphore.acquire ();

To obtain a license, if the number of licenses in the semaphore is already 0, then this function will appear waiting condition;
If permission is obtained, the number of licenses for this semaphore is minus one;

Semaphore.release ();

Indicates that a license is released, and if the previous semaphore has a license number of 0, then the call to Semaphore.release ()
function, the number of licenses in the semaphore becomes 1; In short, the number of licenses in this semaphore is based on the original
Add one, regardless of what the initial value is before the semaphore;

Semaphore.availablepermits ();

Represents the number of licenses that the semaphore semaphore now has

3, the applicable scene:

5 people at the same time to the bank to transact business, but the bank only 2 salesman, the beginning, 2 people at the same time, then, any one business completed, immediately handle the next.

4, code example:

Package Com.test.thread.semaphore;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

Import Java.util.concurrent.Semaphore; /** * @author Javaloveiphone * @date Date Created: February 7, 2017 morning 10:38:53 * @Description: Semaphore semaphore Control Thread Concurrent Use example * * Public CLA SS Semaphoretest {public static void main (string[] args) throws Interruptedexception {//create thread pool int C
        Ount = 5;

        Executorservice ThreadPool = Executors.newfixedthreadpool (count);
        Control semaphore, that is, the number of concurrent threads is 2 semaphore bankers = new semaphore (2);
        Current customer number int consumer = 0;
        SYSTEM.OUT.PRINTLN ("Idle salesman has:" +bankers.availablepermits () + "bit");
            Number of customers for (int i=1;i<=count;i++) {consumer = i;
            Bank Bank = new Bank (Bankers,consumer);
        Threadpool.execute (bank);
        } thread.sleep (1000);
        Close the thread pool Threadpool.shutdown ();
SYSTEM.OUT.PRINTLN ("Idle salesman has:" +bankers.availablepermits () + "bit");    } class Bank implements runnable{//bank clerk private Semaphore bankers;

    Current customer private int consumer;
        Public Bank (Semaphore Bankers,int consumer) {this.bankers = bankers;
    This.consumer = consumer; @Override public void Run () {//Customer pick-up phase, does not control concurrent quantity System.out.println ("= = = Customer Enter bank first, number:" +consum
        er+ ", please wait for the station =========");
            try {//Customer handling business phase, limit up to 2 customers at the same time Business//above two comments, you can find more fine-grained control threads concurrent number//salesman start service, occupied

            Bankers.acquire ();
            System.out.println ("Customer:" +consumer+ "start to handle business, start");
            System.out.println ("Still left salesman:" +bankers.availablepermits () + "bit");
            Thread.Sleep (100);

            System.out.println ("Customer:" +consumer+ "processing business completed, end");
        After the completion of the business, the salesman released, ready for the next customer service bankers.release ();
        catch (Interruptedexception e) {e.printstacktrace ();
 }
    }
}

The possible results are printed as follows:

Idle salesman has: 2
customers to enter the bank of the first number, Number: 1, please wait for the call =========
customers: 1 began to deal with business, start
also left the salesman: 1
customers to enter the bank first number, number: 3, Please wait for the call =========
Customer: 3 start business, start
still left salesman: 0
= = Customers Enter the bank first get number, Number: 2, please wait for the call =========
= = Customers Enter the bank first take the number, Number: 4, please wait for a call =========
= = Customer Enter the bank first get the number, Number: 5, please wait for =========
Customer: 1 business completed, end
Customer: 3 business completed, end
Customer: 2 Start to transact business, start
Customer: 4 start business, start
still left salesman: 0 is
still left salesman: 0
Customers: 2 business finished, end
Customer: 4 business completed,
end Customer: 5 Start business, start
still left salesman: 1
Customers: 5 business completed, end
idle salesman has: 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.