码迷,mamicode.com
首页 > 编程语言 > 详细

java并发之Semaphore

时间:2015-03-18 22:58:09      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

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的方法都应该是同步的。

java并发之Semaphore

标签:

原文地址:http://www.cnblogs.com/gaoxing/p/4348719.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!