多线程之Semaphore(信号量)应用

(1)业务需求:20人去买票,但是窗口只有两个,当两人中有任意一人买完后,其余十八人任意一人可以继续购买

Semaphore(信号量):用于现在同时访问的一些数目,控制并发访问量

                                    

package com.guoanjia.common.utils;

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

/**
 * @author syliu
 * @Title:
 * @Package SemaphoreDemo
 * @create 2018/5/14 0014
 */
public class SemaphoreDemo {
   /**
    * 控制线程任务
    */
   class SemaphoreRunnable implements Runnable {
      //信号量
      private Semaphore semaphore;
      //用户编号
      private int usernum;

      public SemaphoreRunnable(Semaphore semaphore, int usernum) {
         this.semaphore = semaphore;
         this.usernum = usernum;
      }

      @Override
      public void run() {
         try {
            //获得信号量,相当于获得售票窗口
            semaphore.acquire();
            PrintLogger.info("用户【" + usernum + "】进入窗口买票");
            Thread.sleep((long) (Math.random() * 10000));
            PrintLogger.info("用户【" + usernum + "】买票完成,离开");
            //释放信号量,相当于离开窗口
            semaphore.release();
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }

   public void execute() {
      final Semaphore semaphore = new Semaphore(2);
      //获取缓存线程池
      final ExecutorService executorService = Executors.newCachedThreadPool();
      for (int i = 1; i < 21; i++) {
         executorService.execute(new SemaphoreRunnable(semaphore, i));
      }
      //关闭线程任务
      executorService.shutdown();
   }

   public static void main(String[] args) {
      final SemaphoreDemo semaphoreDemo = new SemaphoreDemo();
      semaphoreDemo.execute();
   }
}
应用场景:限流或者控制并发的线程数

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值