Java concurrent tool Semaphore application instance, tool class semaphore

Source: Internet
Author: User

Java concurrent tool Semaphore application instance, tool class semaphore

1 package com. thread. test. thread; 2 3 import java. util. random; 4 import java. util. concurrent. *; 5 6/** 7 * Semaphore 8 * Semaphore a set of maintainers with permissions without the entity permission. It is only a set of numbers representing the permissions. 9 * each acquire execution is blocked, after obtaining the permission, 10 * each time the release is executed, the permission is released, wake up acquire thread 11*12 * Semaphore is usually used to restrict Resource Access 13*14*15 * Created by windwant on. 16 */17 public class MySemaphore {18 19 public static void main (String [] args) {20 Semaphore sp = new Semaphore (5, true ); // fairness constructor true21 ExecutorService es = Executors. newCachedThreadPool (); 22 Random r = new Random (); 23 for (int I = 0; I <10; I ++) {24 es.exe cute (new Needer (sp, r. nextInt (10), "needer" + I); 25} 26 es. shutdown (); 27} 28} 29 30 class Needer implements Runnable {31 32 private Semaphore sp; 33 34 private int seconds; 35 36 private String neederName; 37 38 Needer (Semaphore sp, int seconds, String neederName) {39 this. sp = sp; 40 this. seconds = seconds; 41 this. neederName = neederName; 42} 43 44 public void run () {45 try {46 sp. acquire (); 47 System. out. println ("needer" + neederName + "begin, need time:" + seconds + "s"); 48 long B = System. currentTimeMillis (); 49 for (int I = 0; I <seconds; I ++) {50 Thread. sleep (1, 1000); 51 System. out. println ("needer: "+ neederName +" ============== "+ I +" ============== "); 52} 53 long d = System. currentTimeMillis ()-B; 54 System. out. println ("needer" + neederName + "over, executing time:" + TimeUnit. SECONDS. convert (d, TimeUnit. MILLISECONDS); 55 sp. release (); 56} catch (InterruptedException e) {57 e. printStackTrace (); 58} 59} 60}

Project address: https://github.com/windwant/threadtest

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.