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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35977237/article/details/80306968

(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();
   }
}
应用场景:限流或者控制并发的线程数

猜你喜欢

转载自blog.csdn.net/qq_35977237/article/details/80306968