【十三】Java多线程J.U.C之 Semaphore

概述

信号量Semaphore的作用是控制最大并发数。

信号量是一个非负整数,所有通过它的线程都会将该整数减一,当该整数值为零时,所有试图通过它的线程都将处于等待状态。

通过 acquire() 获取一个许可(阻塞),如果没有就等待,而 release() 释放一个许可。

可以设置该信号量是否采用公平模式,如果以公平方式执行,则线程将会按到达的顺序(FIFO)执行,如果是非公平,则可以后请求的有可能排在队列的头部。

    /**
     * Creates a {@code Semaphore} with the given number of
     * permits and the given fairness setting.
     *
     * @param permits the initial number of permits available.
     *        This value may be negative, in which case releases
     *        must occur before any acquires will be granted.
     * @param fair {@code true} if this semaphore will guarantee
     *        first-in first-out granting of permits under contention,
     *        else {@code false}
     */
    public Semaphore(int permits, boolean fair) {
        sync = fair ? new FairSync(permits) : new NonfairSync(permits);
    }

代码示例

package com.sid.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @program: thread-test
 * @description: 信号量
 * @author: Sid
 * @date: 2019-01-07 16:50
 * @since: 1.0
 **/
public class SemaphoreDemo {
    public static void main(String[] args) {

        ExecutorService exec = Executors.newCachedThreadPool();
        // 只能20个线程同时访问
        final Semaphore semaphore = new Semaphore(20);

        // 模拟100个客户端访问
        for (int index = 0; index < 100; index++) {
            final int NO = index;
            Runnable run = new Runnable() {
                public void run() {
                    try {
                        // 获取许可
                        semaphore.acquire();
                        System.out.println("Accessing: " + NO);
                        Thread.sleep((long) (Math.random() * 10000));
                        // 访问完后,释放
                        semaphore.release();
                        //availablePermits()指的是当前信号灯库中有多少个可以被使
                        System.out.println("-----------------"+semaphore.availablePermits());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            exec.execute(run);
        }
        exec.shutdown();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值