Semaphore使用

2018-01-23  本文已影响0人  jsjack_wang
1 简介
    一个计数信号量。从概念上讲,信号量维护了一个许可集。如有必要,在许可可用前会阻塞每一个 acquire(),然后再获取该许可。每个 release() 添加一个许可,从而可能释放一个正在阻塞的获取者。但是,不使用实际的许可对象,Semaphore 只对可用许可的号码进行计数,并采取相应的行动。
2 小栗子
public class SemaphoreDemo {

    private static final int PERSON_COUNT = 8;
    private static final int THREAD_POOL_COUNT = 5;

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_COUNT);
        for (int index = 0; index < PERSON_COUNT; index ++) {
            executorService.execute(()->{
                BankOperation.saveMoney();
            });
        }
        executorService.shutdown();
    }
}

class BankOperation {
    private static Semaphore semaphore = null;

    static {
        semaphore = new Semaphore(2, true);
    }

    public static void saveMoney() {
        try {
            semaphore.acquire();
            System.out.println("开始服务, threadId:" + Thread.currentThread().getId());
            Thread.sleep(2000);
            System.out.println("结束服务, threadId:" + Thread.currentThread().getId());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读