Java 多线程并发控制信号量 Semaphore

一、概述

Semaphore 可以控制某个对象(变量,方法,代码块)的并发访问数量,可用作限流。Semaphore在初始化时可以指定多少个许可证。如果需要访问某个被Semaphore控制的对象,线程只有在获取到许可证的情况下才能访问,否则就一直阻塞直到获取到许可证或者线程被中断。Semaphore可以设置公平策略和非公平策略,当设置为false时,Semaphore不会保证线程获取许可证的顺序。

二、构造方法

public Semaphore(int permits):permits 初始化state的值,指定许可数量,默认非公平策略

public Semaphore(int permits, boolean fair):permits 初始化state的值,指定许可数量,fair可指定公平策略或非公平策略。

三、主要方法

public void acquire() throws InterruptedException:从这个Semaphore中获取一个许可证,如果没有可用许可则阻塞,直到有一个可用许可或调用线程中断。调用线程中断时抛出InterruptedException异常。

public void acquire(int permits) throws InterruptedException:从这个Semaphore中获取permits个许可证。否则阻塞直到这些个许可可用或调用线程被中断。线程被中断抛出InterruptedException异常,permits小于零抛出IllegalArgumentException异常。

public void release():释放一个许可证,返回给Semaphore对象,可用许可证的数量加一。

public int availablePermits():返回当前可用的许可数量。

public boolean tryAcquire():???仅当调用时有一个许可证可用的情况,才能从这个Semaphore中获取这个可用的许可证。成功获取返回true,否则返回false ???

四、代码

package com.scott.current;

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

public class SemaphoreDemo2 {
    public static void main(String[] args) {

        ExecutorService executorService = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(2);

        for (int index = 0; index < 5; index++) {
            final int NO = index;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
//                        semaphore.tryAcquire();
                        System.out.println(Thread.currentThread().getName() + "\t" + "Accessing:" + NO + "\t" + "时间:" + System.currentTimeMillis());
                        Thread.sleep((long) (Math.random() * 10000));
                        semaphore.release();
                        System.out.println(Thread.currentThread().getName() + "------------------" + semaphore.availablePermits() + "\t" + "时间:" + System.currentTimeMillis());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            executorService.execute(runnable);
            System.out.println(Thread.currentThread().getName() + "第" + (index + 1) + "次循环");
        }
        executorService.shutdown();
    }
}

执行结果:

由执行结果可以看出,后面的都是释放一个许可证两外一个线程才能获得一个可用的许可证。算了,遍不下去了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值