57.Semaphore信号量

作者 : admin 本文共400个字,预计阅读时间需要1分钟 发布时间: 2024-06-10 共1人阅读

用来限制能同时访问共享资源的线程上限。只是适合限制单机线程数量。

@Slf4j
public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i  {
                try {
                    semaphore.acquire();//获得此信号量
                    log.debug("我是线程"+Thread.currentThread().getName());

                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();//释放信号量
                }

            }).start();
        }
    }
}

57.Semaphore信号量插图

Semaphore实现简单连接池,对比享元模式下的实现用wait,notify。性能和可读性显然更好。

本站无任何商业行为
个人在线分享 » 57.Semaphore信号量
E-->