Java Concurrent Programming-semaphore

Source: Internet
Author: User

Semaphore literal translation is a semaphore, its function is better understood, is to set a number of permits by the constructor, and then through the acquire method to obtain permission, release method releases the license. It also has Tryacquire and acquireuninterruptibly methods that can be selected according to your needs.
The following is a simulation of a connection pool, control can only have a maximum of 50 threads at a time, the main thread creates a child thread per millisecond, a connection pool of 50 licenses, each get connected sub-thread ball 300ms, connection wait timeout 500ms.

[Java]import java.util.uuid;import Java.util.concurrent.semaphore;import Java.util.concurrent.timeunit;public Class Testsemaphore extends Thread {public static void main (string[] args) {int i = 0;while (i <) {I++;new Testsema Phore (). Start (); try {thread.sleep (1);} catch (Interruptedexception e) {e.printstacktrace ();}}} /** * Control the number of simultaneous access to a resource class control at the same time there can be only 50 access */static Semaphore Semaphore = new Semaphore (a); static int timeout = 500;public vo ID run () {try {Object Connec = getconnection (); System.out.println ("Get a Connection" + Connec); Thread.Sleep (+); releaseconnection (Connec);} catch (Interruptedexception e) {e.printstacktrace ();}} public void Releaseconnection (Object connec) {/* release license */semaphore.release (); System.out.println ("Release a Connection" + Connec); Public Object getconnection () {try {* * * get license */boolean getaccquire = Semaphore.tryacquire (timeout, timeunit.milliseconds) ; if (Getaccquire) {return Uuid.randomuuid (). toString ();}} catch (Interruptedexception e) {e.printstacktrace ();} throw new IllegalarguMentexception ("timeout");}} [/java]

Java concurrent Programming-semaphores

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.