java并发之Semaphore

public class SemaphoreTest {
    private static final int MAX_AVAILABLE=100;
    private final Semaphore available=new Semaphore(MAX_AVAILABLE,true);
    
    @Test
    public void test1()
    {
        ExecutorService threadPool=Executors.newCachedThreadPool();
        for (int i = 0; i < 300; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        available.acquire();
                        System.out.println("save data");
                        available.release();
                    } catch (InterruptedException e) {
                    }
                }
            });
        }

        threadPool.shutdown();
    }
}

Semaphore字面意思是信号量,该信号量表示有多少个线程可以访问该资源,有点想object的wait和notify.不过object的只有一个线程可用Semaphore是多个线程可用。

Semaphore的方法都应该是同步的。

posted @ 2015-03-18 21:40  高兴的博客  阅读(285)  评论(0编辑  收藏  举报