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