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

版权声明:转载注明出处 https://blog.csdn.net/jy02268879/article/details/86011546

概述

信号量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();
    }
}

猜你喜欢

转载自blog.csdn.net/jy02268879/article/details/86011546