Java thread concurrency Semaphore class example _java

Source: Internet
Author: User
Tags semaphore

Copy Code code as follows:

Package Com.yao;

Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Semaphore;

/**
* Java 5.0 adds 4 synchronization devices that coordinate the process between threads, respectively:
* Semaphore, Countdownlatch, Cyclicbarrier and exchanger.
* This example mainly introduces semaphore.
* Semaphore is a tool used to manage a resource pool and can be viewed as a pass,
* Threads to get resources from the resource pool must first get the pass,
* If the thread cannot get the pass temporarily, the thread will be blocked into the waiting state.
*/
public class Mysemaphore extends Thread {

private int i;
Private semaphore semaphore;

Public Mysemaphore (int i,semaphore semaphore) {
THIS.I = i;
This.semaphore = semaphore;
}

public void Run () {
if (semaphore.availablepermits () > 0) {
System.out.println ("" "+i+" has vacancy: ");
}else{
System.out.println ("" +i+ "waiting, no Vacancy");
}
try {
Semaphore.acquire ();
catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println ("" +i+ "to get Vacant");
try {
Thread.Sleep ((int) math.random () *10000);
catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println ("" +i+ "use complete");
Semaphore.release ();
}
public static void Main (string[] args) {
Semaphore semaphore = new semaphore (2);
Executorservice service = Executors.newcachedthreadpool ();
for (int i = 0; i<10 i++) {
Service.execute (New Mysemaphore (I,semaphore));
}
Service.shutdown ();
semaphore.acquireuninterruptibly (2);
SYSTEM.OUT.PRINTLN ("Use completed, need to clean up");
Semaphore.release (2);
}

}

Related Article

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.