Java-Semaphore的使用

Semaphore

  • Semaphore(信号量)是用来控制同时访问特定资源的线程数量,它通过协调各个线程,以保证合理的使用公共资源
  • 不要将SemaPhore和服务限流关联起来
  • Semaphore控制访问资源的并发数,而RateLimiter控制访问资源的速度。

样例代码

public class SemaphoreTest {

    @Test
    public void test1() {
        final int THREAD_COUNT = 30;
        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);
        final Semaphore s = new Semaphore(10);
        final CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT);

        long startTime = System.currentTimeMillis();
        for( int i = 0; i < THREAD_COUNT; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        s.acquire();
                        System.out.println("save data");
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                        System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
                        Thread.sleep(1000);
                        countDownLatch.countDown();
                    } catch (InterruptedException e) {
                    } finally {
                        s.release();
                    }
                }
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime);
        executorService.shutdown();

    }
}

你可能感兴趣的:(Java-Semaphore的使用)