Java Multithreading--the use of semaphore semaphore

Source: Internet
Author: User
Tags semaphore

  Semaphore can control how many times a shared resource can be accessed concurrently, to maintain the number of threads currently accessing a shared resource, and to provide a synchronization mechanism. For example, control the number of concurrent accesses allowed for a file.

For example, there are 100 machines in the Internet bar, so the maximum can only provide 100 people at the same time the Internet, when the 101th guest, it is necessary to wait, once a person under the machine, you can immediately get an empty camera to fill up. This is the concept of semaphore.

The Semaphore class is located in the Java.util.concurrent package. The following example uses this class:

 PackageCom.wang.thread;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.Semaphore;/*** Create 10 threads with a maximum of three threads executing function code at the same time *@authorAdministrator **/ Public classSemaphoretest { Public Static voidMain (string[] args) {//Create a resizable buffer thread poolExecutorservice Service =Executors.newcachedthreadpool (); //only three threads can access simultaneously        FinalSemaphore SP =NewSemaphore (3); //loop Create a thread         for(inti=0;i<10;i++) {Runnable Runnable=NewRunnable () { Public voidrun () {Try {                        //get a license, get permission to go down, block without getting it, wait for the semaphore to empty the available licensesSp.acquire (); } Catch(interruptedexception E1) {e1.printstacktrace (); }                    //function CodeSYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "Enter, current already" + (3-sp.availablepermit S ()) + "concurrency"); Try{Thread.Sleep (Long) (Math.random () *10000)); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Threads" + thread.currentthread (). GetName () + "About to leave"); //Execute function code, return licensesp.release (); //The following code is sometimes executed inaccurately because it does not synthesize atomic units with the above codeSYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "left, current" + (3-sp.availablepermi TS ()) + "concurrency");            }            };                    Service.execute (runnable); }    }}

If you initialize the semaphore of this class to 1, that is, the parameter passed in the constructor is 1, so that it is used with at most one available license, then it can be used as a mutually exclusive lock, analogous to lock lock.

Code Demo:

 Packagequeue;ImportJava.awt.image.SampleModel;ImportJava.util.concurrent.ArrayBlockingQueue;ImportJava.util.concurrent.BlockingQueue;ImportJava.util.concurrent.Semaphore;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock;/*** The code in the test class in the off-the- shelf program is constantly generating data and then handing it over to the Testdo.dosome () method, as if the producer is constantly generating data, and consumers are consuming data. Please change the program to 10 threads to consume the data generated by the generator, * These consumers call the Testdo.dosome () method to process, so each consumer needs a second to finish, * The program should ensure that these consumer threads in order to consume data sequentially, only the last consumer after consumption, The next consumer will be able to consume data, * who can be the next consumer, but make sure that the data that these consumer threads get is in order. * @authorAdministrator*/ Public classTest { Public Static voidMain (string[] args) {FinalBlockingqueue<string> queue=NewArrayblockingqueue<string> (10); //final Lock lock=new reentrantlock ();        FinalSemaphore sp=NewSemaphore (1);  for(inti=0;i<10;i++){            NewThread (NewRunnable () {@Override Public voidrun () {Try {                        //Lock.lock ();Sp.acquire (); String input=Queue.take (); String Output=testdo.dosome (input); System.out.println (Thread.CurrentThread (). GetName ()+ ":" +output); //Lock.unlock ();sp.release (); } Catch(interruptedexception e) {e.printstacktrace ();        }}). Start (); } System.out.println ("Begin:" + (System.currenttimemillis ()/1000));  for(inti=0;i<10;i++) {//this can't be changed.String input = i+ "";//this can't be changed.            Try{queue.put (input); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }}//cannot change this testdo classclassTestdo { Public Staticstring Dosome (String input) {Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } String Output= input + ":" + (System.currenttimemillis ()/1000); returnoutput; }}

The functionality of the semaphore in the code can also be implemented with lock locks, as shown in the commented out code section.

Http://www.apihome.cn/api/java/Semaphore.html This link is the Chinese API documentation for this class and can be seen.

Java Multithreading--the use of semaphore semaphore

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.