首页 > 编程语言 > 详细

java并发之Semaphore

时间:2015-03-18 22:55:30      阅读:271      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!