Semaphore两个重要的方法就是
semaphore.acquire() 请求一个信号量,这时候的信号量个数-1(一旦没有可使用的信号量,也即信号量个数变为负数时,再次请求的时候就会阻塞,直到其他线程释放了信号量)
semaphore.release() 释放一个信号量,此时信号量个数+1
- public class SemaphoreTest {
- private Semaphore mSemaphore = new Semaphore(5);
- public void run(){
- for(int i=0; i< 100; i++){
- new Thread(new Runnable() {
- @Override
- public void run() {
- test();
- }
- }).start();
- }
- }
-
- private void test(){
- try {
- mSemaphore.acquire();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName() + " 进来了");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName() + " 出去了");
- mSemaphore.release();
- }
- }
示例中实例化了具有5个信号量的semaphore,保证只有5个线程在执行test方法
- 04-18 17:05:46.350 14192-14228/com.tongxt.myapplication I/System.out: Thread-1228 进来了
- 04-18 17:05:46.351 14192-14231/com.tongxt.myapplication I/System.out: Thread-1231 进来了
- 04-18 17:05:46.354 14192-14233/com.tongxt.myapplication I/System.out: Thread-1233 进来了
- 04-18 17:05:46.354 14192-14232/com.tongxt.myapplication I/System.out: Thread-1232 进来了
- 04-18 17:05:46.355 14192-14234/com.tongxt.myapplication I/System.out: Thread-1234 进来了
-
- 04-18 17:05:47.351 14192-14228/com.tongxt.myapplication I/System.out: Thread-1228 出去了
- 04-18 17:05:47.351 14192-14236/com.tongxt.myapplication I/System.out: Thread-1236 进来了
- 04-18 17:05:47.352 14192-14231/com.tongxt.myapplication I/System.out: Thread-1231 出去了
- 04-18 17:05:47.352 14192-14235/com.tongxt.myapplication I/System.out: Thread-1235 进来了
- 04-18 17:05:47.354 14192-14233/com.tongxt.myapplication I/System.out: Thread-1233 出去了
- 04-18 17:05:47.354 14192-14237/com.tongxt.myapplication I/System.out: Thread-1237 进来了
- 04-18 17:05:47.354 14192-14232/com.tongxt.myapplication I/System.out: Thread-1232 出去了
- 04-18 17:05:47.354 14192-14229/com.tongxt.myapplication I/System.out: Thread-1229 进来了
- 04-18 17:05:47.356 14192-14234/com.tongxt.myapplication I/System.out: Thread-1234 出去了
- 04-18 17:05:47.356 14192-14230/com.tongxt.myapplication I/System.out: Thread-1230 进来了
- 04-18 17:05:48.351 14192-14236/com.tongxt.myapplication I/System.out: Thread-1236 出去了
本文介绍了一个使用Semaphore控制并发线程数量的示例。Semaphore通过限制同时执行的线程数来防止资源过载,当线程调用acquire()时会等待直至有可用许可,而release()则释放一个许可。示例代码创建了具有5个许可的Semaphore,确保任意时刻最多只有5个线程在执行特定方法。
9136

被折叠的 条评论
为什么被折叠?



