Java并发工具类Semaphore应用实例

2020-09-11 10:48:08 浏览数 (1)

代码语言:javascript复制
 1 package com.thread.test.thread;
 2 
 3 import java.util.Random;
 4 import java.util.concurrent.*;
 5 
 6 /**
 7  * Semaphore
 8  * Semaphore维护者一组权限,无实体权限,只是一组代表权限的数字,
 9  * 每一次执行acquire都会被阻塞,直到获取获取权限,
10  * 每一次执行release都会释放权限,唤醒阻塞acquire线程
11  *
12  * Semaphore通常应用于限制资源访问
13  *
14  *
15  * Created by windwant on 2016/5/27.
16  */
17 public class MySemaphore {
18 
19     public static void main(String[] args) {
20         Semaphore sp = new Semaphore(5, true);  //公平性 构造函数 true
21         ExecutorService es = Executors.newCachedThreadPool();
22         Random r = new Random();
23         for (int i = 0; i < 10; i  ){
24             es.execute(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(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 }

项目地址:https://github.com/windwant/windwant-demo/tree/master/thread-demo

0 人点赞