java 线程同步工具Semaphore

一个计数信号量。从概念上讲,信号量维护了一个许可集。如有必要,在许可可用前会阻塞每一个 acquire(),然后再获取该许可。每个 release() 添加一个许可,从而可能释放一个正在阻塞的获取者。但是,不使用实际的许可对象,Semaphore 只对可用许可的号码进行计数,并采取相应的行动。

(jdk api)

简单来说  : Semaphore 通常用于限制可以访问某些资源(物理或逻辑的)的线程数目(说明:同一个资源被10个线程同时访问 但是现在要求,同时并发可以访问资源的线程限制3个线程其他的线程处于等待状态 ,当访问资源的线程有一个结束其他等待的线程就会有一个线程加入 )

代码示例:

package tt.conCurrent_Test;

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

public class Semaphore_Test {
    public static void main(String[] agrs){
       final  Semaphore sm =new Semaphore(3);
        ExecutorService execute = Executors.newCachedThreadPool();
        for(int i=0;i<10;i++){
            execute.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        sm.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("当前线程"+Thread.currentThread().getName()+"进入 当前有"+(3-sm.availablePermits())+"个线程同时并发");
                    try {
                        Thread.sleep((long)Math.random()*1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("当前线程"+Thread.currentThread().getName()+"即将离开");
                    sm.release();
                    System.out.println("当前线程"+Thread.currentThread().getName()+"已离开   当前有"+(3-sm.availablePermits())+"个线程同时并发");
                }
            });
        }

    }
}

运行结果:
当前线程pool-1-thread-1进入 当前有1个线程同时并发
当前线程pool-1-thread-3进入 当前有2个线程同时并发
当前线程pool-1-thread-3即将离开
当前线程pool-1-thread-3已离开   当前有1个线程同时并发
当前线程pool-1-thread-4进入 当前有2个线程同时并发
当前线程pool-1-thread-1即将离开
当前线程pool-1-thread-1已离开   当前有1个线程同时并发
当前线程pool-1-thread-4即将离开
当前线程pool-1-thread-4已离开   当前有0个线程同时并发
当前线程pool-1-thread-2进入 当前有1个线程同时并发
当前线程pool-1-thread-5进入 当前有2个线程同时并发
当前线程pool-1-thread-3进入 当前有3个线程同时并发
当前线程pool-1-thread-5即将离开
当前线程pool-1-thread-5已离开   当前有2个线程同时并发
当前线程pool-1-thread-2即将离开
当前线程pool-1-thread-3即将离开
当前线程pool-1-thread-4进入 当前有3个线程同时并发
当前线程pool-1-thread-1进入 当前有3个线程同时并发
当前线程pool-1-thread-1即将离开
当前线程pool-1-thread-1已离开   当前有2个线程同时并发
当前线程pool-1-thread-6进入 当前有3个线程同时并发
当前线程pool-1-thread-6即将离开
当前线程pool-1-thread-6已离开   当前有2个线程同时并发
当前线程pool-1-thread-4即将离开
当前线程pool-1-thread-4已离开   当前有1个线程同时并发
当前线程pool-1-thread-5进入 当前有3个线程同时并发
当前线程pool-1-thread-3已离开   当前有2个线程同时并发
当前线程pool-1-thread-5即将离开
当前线程pool-1-thread-5已离开   当前有0个线程同时并发
当前线程pool-1-thread-2已离开   当前有2个线程同时并发



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值