Java并发编程之信号量Semaphore

2022-12-30 10:56:49

Semaphore可以控制某个方法允许并发访问线程的个数,
Semaphore semaphore = new Semaphore(5, true); 当方法进入时,请求一个信号,如果信号被用完则等待,方法运行完,释放一个信号,释放的信号新的线程就可以使用。

public class SemaphoreDemo {

    public static void main(String[] args) {

        int threadCount = 20;

        final Semaphore semaphore = new Semaphore(5, true);

        for (int i = 0; i < threadCount; i++) {

            Thread thread = new Thread() {
                @Override
                public void run() {
                    try {

                        /**
                         * 在 semaphore.acquire() 和 semaphore.release()之间的代码,同一时刻只允许指定个数的线程进入
                         * */
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + ":doSomething start-" + LocalDateTime.now() );
                        Thread.sleep(2000); // 模拟耗时操作
                        System.out.println(Thread.currentThread().getName() + ":doSomething end-" + LocalDateTime.now() );
                        semaphore.release();

                    } catch (Exception e) {

                    }
                }
            };
            thread.start();

        }

    }

}

根据输出可以看到同一时间只有指定个数的线程执行semaphore.acquire()和semaphore.release()之间的代码。

  • 作者:yzpyzp
  • 原文链接:https://blog.csdn.net/yzpbright/article/details/104643699
    更新时间:2022-12-30 10:56:49