Introduction to Java semaphores Semaphore

Source: Internet
Author: User

Introduction to Java semaphores Semaphore

The semaphore class also appears in java1.5, which is located in the java. util. concurrent package.

First, let's take a look at his document explanation:

A count semaphore. In terms of concept, semaphores maintain a license set. If necessary, eachacquire()And then obtain the license. Eachrelease()Add a license to release a blocked recipient. However, do not use the actual license object,SemaphoreIt only counts available license numbers and takes corresponding actions. There are two very important methods: acquire and release.

Now let's take a look at the introduction of these two methods.

 

public void acquire()             throws InterruptedException
From this semaphore, a license is obtained, and the thread is blocked until a license is provided. Otherwise, the thread is interrupted. Get a license (if one is provided) and return immediately, reduce the number of available licenses by 1.

 

If no license is available, you are prohibited from using the current thread for Thread Scheduling purposes and putting it in sleep state before one of the following two cases:

  • Some other threads call this semaphorerelease()Method, and the current thread is the next thread to be allocated with a license; or some other threads interrupt the current thread.

    If the current thread:

    • This method sets its interrupted status to on, or isInterrupted.

      ThrowInterruptedExceptionAnd clear the interrupted status of the current thread.

      Throw:InterruptedException-If the current thread is interrupted
      public void release()
      Release a license and return it to the semaphore. Release a license and increase the number of available licenses by 1. If any thread tries to obtain the license, select a thread and give it the license just released. Then enable (or re-enable) the thread for the purpose scheduled by the thread.

       

      Threads that do not require the release of the license must callacquire()To obtain the license. Establish the correct usage of semaphores through programming conventions in applications.

      Now let's write an example to verify it.

       

      In the preceding example, only five threads are allowed to access the code between acquire () and release () at the same time.

       

      Package cn.kge.com. thread; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. semaphore; public class ThreadSemaphoreTest {public static void main (String [] args) {// thread pool ExecutorService exec = Executors. newCachedThreadPool (); // only five threads can simultaneously access final Semaphore semp = new Semaphore (5); // simulate 20 clients to access for (int index = 0; index <20; index ++) {final int NO = index; Runnable run = new Runnable () {public void run () {try {// obtain the license semp. acquire (); System. out. println ("Thread" + Thread. currentThread (). getName () + "Enter, current"); Thread. sleep (long) (Math. random () * 10000); // release after access. If the following statements are blocked, only five records can be printed on the console, and then the thread will be congested. out. println ("Thread" + Thread. currentThread (). getName () + "coming soon"); semp. release () ;}catch (InterruptedException e) {}}; exec.exe cute (run) ;}// exit the thread pool exec. shutdown ();}}

      Result:

       

      Thread pool-1-thread-1 entry, which currently has
      Thread pool-1-thread-2 entry, the current has
      Thread pool-1-thread-4 entry, the current has
      Thread pool-1-thread-6 entry, the current has
      Thread pool-1-thread-5 entry, the current has
      Thread pool-1-thread-6 is about to exit
      Thread pool-1-thread-8 entry, the current has
      Thread pool-1-thread-4 is about to exit
      Thread pool-1-thread-9 entry, the current has
      Thread pool-1-thread-8 is about to exit
      Thread pool-1-thread-10 entry, the current has
      Thread pool-1-thread-5 is about to exit
      Thread pool-1-thread-3 entry, which currently has
      Thread pool-1-thread-1 is about to exit
      Thread pool-1-thread-7 entry, which currently has
      Thread pool-1-thread-2 is about to exit
      Thread pool-1-thread-13 entry, the current has
      Thread pool-1-thread-13 is about to exit
      Thread pool-1-thread-12 entry, the current has
      Thread pool-1-thread-10 is about to exit
      Thread pool-1-thread-11 entry, the current has
      Thread pool-1-thread-3 is about to exit
      Thread pool-1-thread-14 entry, the current has
      Thread pool-1-thread-12 is about to exit
      Thread pool-1-thread-16 entry, the current has
      Thread pool-1-thread-7 is about to exit
      Thread pool-1-thread-17 enters, and the current
      Thread pool-1-thread-9 is about to exit
      Thread pool-1-thread-18, which is already in use
      Thread pool-1-thread-16 is about to exit
      Thread pool-1-thread-15 entry, the current has
      Thread pool-1-thread-14 is about to exit
      Thread pool-1-thread-19 to enter, the current already exists
      Thread pool-1-thread-18 is about to exit
      Thread pool-1-thread-20, which is currently in use
      Thread pool-1-thread-11 is about to exit
      Thread pool-1-thread-17 is about to exit
      Thread pool-1-thread-15 is about to exit
      Thread pool-1-thread-19 is about to exit
      Thread pool-1-thread-20 is about to exit

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.