一个类说明Java 信号量 Semaphore 的用法
星期五, 2015-04-10 | Author: Lee | JAVA-and-J2EE | 5,997 views
在用Semaphore 信号量的时候,感觉对公平调度比较有用,可以控制多线程争夺资源时候,最大可以几个在执行,随手写了代码测试下,如下:
说明: 1. acquire() 获取一个许可,如果没有就等待
2. release() 释放一个许可
3. Semaphore可以控制某个资源可被同时访问的个数,自行初始化的数量,为1当然就顺序执行了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | package com.i5a6.semp.test; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; public class SemaphoreTest { private Semaphore semp; private ExecutorService executorPool; public SemaphoreTest(int threadNum) { semp = new Semaphore(threadNum); executorPool = Executors.newFixedThreadPool(threadNum); } public void doEnd() { this.executorPool.shutdown(); } public void doMsg(int num) { try { semp.acquire(); executorPool.execute(new HelloUExecutor(num)); } catch (InterruptedException e) { e.printStackTrace(); } } class HelloUExecutor implements Runnable { private int num; public HelloUExecutor(int num) { this.num = num; } Random r = new Random(); @Override public void run() { try { System.out.println(num); Thread.sleep(r.nextInt(1000)); } catch (Exception e) { e.printStackTrace(); } finally { semp.release(); } } } public static void main(String[] args) { // 初始化为1 顺序执行 SemaphoreTest st = new SemaphoreTest(5); for (int i = 0; i < 20; i++) { st.doMsg(i); } st.doEnd(); } } |
文章作者: Lee
本文地址: https://www.pomelolee.com/1438.html
除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址
No comments yet.
Leave a comment
Search
相关文章
热门文章
最新文章
文章分类
- ajax (10)
- algorithm-learn (3)
- Android (6)
- as (3)
- computer (85)
- Database (30)
- disucz (4)
- enterprise (1)
- erlang (2)
- flash (5)
- golang (3)
- html5 (18)
- ios (4)
- JAVA-and-J2EE (186)
- linux (143)
- mac (10)
- movie-music (11)
- pagemaker (36)
- php (50)
- spring-boot (2)
- Synology群晖 (2)
- Uncategorized (6)
- unity (1)
- webgame (15)
- wordpress (33)
- work-other (2)
- 低代码 (1)
- 体味生活 (40)
- 前端 (21)
- 大数据 (8)
- 游戏开发 (9)
- 爱上海 (19)
- 读书 (4)
- 软件 (3)