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

Semaphore两个重要的方法就是

semaphore.acquire() 请求一个信号量,这时候的信号量个数-1(一旦没有可使用的信号量,也即信号量个数变为负数时,再次请求的时候就会阻塞,直到其他线程释放了信号量)

semaphore.release() 释放一个信号量,此时信号量个数+1


 
 
  1. public class SemaphoreTest {
  2. private Semaphore mSemaphore = new Semaphore( 5);
  3. public void run(){
  4. for( int i= 0; i< 100; i++){
  5. new Thread( new Runnable() {
  6. @Override
  7. public void run() {
  8. test();
  9. }
  10. }).start();
  11. }
  12. }
  13. private void test(){
  14. try {
  15. mSemaphore.acquire();
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. System.out.println(Thread.currentThread().getName() + " 进来了");
  20. try {
  21. Thread.sleep( 1000);
  22. } catch (InterruptedException e) {
  23. e.printStackTrace();
  24. }
  25. System.out.println(Thread.currentThread().getName() + " 出去了");
  26. mSemaphore.release();
  27. }
  28. }

示例中实例化了具有5个信号量的semaphore,保证只有5个线程在执行test方法


 
 
  1. 04- 18 17: 05: 46.350 14192- 14228/com.tongxt.myapplication I/System.out: Thread- 1228 进来了
  2. 04- 18 17: 05: 46.351 14192- 14231/com.tongxt.myapplication I/System.out: Thread- 1231 进来了
  3. 04- 18 17: 05: 46.354 14192- 14233/com.tongxt.myapplication I/System.out: Thread- 1233 进来了
  4. 04- 18 17: 05: 46.354 14192- 14232/com.tongxt.myapplication I/System.out: Thread- 1232 进来了
  5. 04- 18 17: 05: 46.355 14192- 14234/com.tongxt.myapplication I/System.out: Thread- 1234 进来了

 
 
  1. 04- 18 17: 05: 47.351 14192- 14228/com.tongxt.myapplication I/System.out: Thread- 1228 出去了
  2. 04- 18 17: 05: 47.351 14192- 14236/com.tongxt.myapplication I/System.out: Thread- 1236 进来了
  3. 04- 18 17: 05: 47.352 14192- 14231/com.tongxt.myapplication I/System.out: Thread- 1231 出去了
  4. 04- 18 17: 05: 47.352 14192- 14235/com.tongxt.myapplication I/System.out: Thread- 1235 进来了
  5. 04- 18 17: 05: 47.354 14192- 14233/com.tongxt.myapplication I/System.out: Thread- 1233 出去了
  6. 04- 18 17: 05: 47.354 14192- 14237/com.tongxt.myapplication I/System.out: Thread- 1237 进来了
  7. 04- 18 17: 05: 47.354 14192- 14232/com.tongxt.myapplication I/System.out: Thread- 1232 出去了
  8. 04- 18 17: 05: 47.354 14192- 14229/com.tongxt.myapplication I/System.out: Thread- 1229 进来了
  9. 04- 18 17: 05: 47.356 14192- 14234/com.tongxt.myapplication I/System.out: Thread- 1234 出去了
  10. 04- 18 17: 05: 47.356 14192- 14230/com.tongxt.myapplication I/System.out: Thread- 1230 进来了
  11. 04- 18 17: 05: 48.351 14192- 14236/com.tongxt.myapplication I/System.out: Thread- 1236 出去了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值