Chinaunix首页 | 论坛 | 博客
  • 博客访问: 176231
  • 博文数量: 43
  • 博客积分: 1428
  • 博客等级: 上尉
  • 技术积分: 410
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-02 09:33
文章分类

全部博文(43)

文章存档

2014年(3)

2013年(3)

2011年(1)

2010年(36)

分类: Android平台

2013-11-08 10:12:50

**********************************
java.util.concurrent.Semaphore
**********************************
一个计数信号量。信号量维护了一个许可集。在允许得数量范围内acquire()可立即获取许可,超出时在获取可用许可前会阻塞在每一个 acquire(),然后再获取该许可,同时许可集中会减少一个许可,每调用一个release() 许可集中会添加一个许可。如果一个acquire()还在阻塞没有获取许可对象得同时调用了release()那么会释放一个正在阻塞的获取者,但是,不使用实际的许可对象,Semaphore 只对可用许可的号码进行计数,并采取相应的行动。一般用Semaphore来控制某个对象的线程访问对象。
 
 
例如:
 
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
 
public class TestSemaphore {
 
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        TestSemaphore t = new TestSemaphore();
        final BoundedHashSet set = t.getSet();
 
        for (int i = 0; i < 4; i++) {        //四个线程同时进行add操作
            exec.execute(new Runnable() {
                public void run() {
                    try {
                        set.add(Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
 
        for (int j = 0; j < 4; j++) {        //四个线程同时进行remove操作
            exec.execute(new Runnable() {
                public void run() {
                    set.remove(Thread.currentThread().getName());
                }
            });
        }
        exec.shutdown();
    }
 
    public BoundedHashSet getSet() {
        return new BoundedHashSet(2);        //定义一个边界约束为2的线程
    }
 
    class BoundedHashSet {
        private final Set set;
        private final Semaphore semaphore;
 
        public BoundedHashSet(int bound) {
            this.set = Collections.synchronizedSet(new HashSet());
            this.semaphore = new Semaphore(bound, true);
        }
 
        public void add(T o) throws InterruptedException {
            semaphore.acquire();            //用信号量来控制同时可以访问的线程得个数
            set.add(o);
            System.out.printf("add:%s%n",o);
        }
 
        public void remove(T o) {
            if (set.remove(o))
                semaphore.release();        //释放信号量
            System.out.printf("remove:%s%n",o);
        }
    }
}
阅读(1478) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~