如何控制某个方法允许并发访问线程的个数?--Semaphore

. package com.yange;
2.
3. import java.util.concurrent.Semaphore;
4. /**
5. * 
6. *
7. */
8. 
9. public class SemaphoreTest {
10. /*
11. * permits the initial number of permits available. This value may be negative, 
12. in which case releases must occur before any acquires will be granted.
13. fair true if this semaphore will guarantee first-in first-out granting of 
14. permits under contention, else false
15. */
16. static Semaphore semaphore = new Semaphore(5,true);
17. public static void main(String[] args) {
18. for(int i=0;i<100;i++){
19. new Thread(new Runnable() {
20.
20. @Override
21. public void run() {
22. test();
23. }
24. }).start();
25. }
27.
26. }
29.
27. public static void test(){
28. try {
29. //申请一个请求
30. semaphore.acquire();
31. } catch (InterruptedException e1) {
32. e1.printStackTrace();
33. }
34. System.out.println(Thread.currentThread().getName()+"进来了");
35. try {
36. Thread.sleep(1000);
37. } catch (InterruptedException e) {
38. e.printStackTrace();
39. }
40. System.out.println(Thread.currentThread().getName()+"走了");
41. //释放一个请求
42. semaphore.release();
43. }
44. }

可以使用 Semaphore 控制,第 16 行的构造函数创建了一个 Semaphore 对象,并且初始化了 5 个信号。这样的
效果是控件 test 方法最多只能有 5 个线程并发访问,对于 5 个线程时就排队等待,走一个来一下。第 33 行,请求一个信号(消费一个信号),如果信号被用完了则等待,第 45 行释放一个信号,释放的信号新的线程就可以使用了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值