2021-07-10

java并发:线程同步机制之Semaphore

一、初识Semaphore

小结:

A、可以将信号量可视化为一个计数器,它可以递增或递减。

B、从概念上讲,信号量维护了一个许可集合,Semaphore对可用的许可进行计数。

C、当计数器的值为0时,它能够使线程等待。

二、示例

The three steps you must follow when you use a semaphore to implement a critical section and protect the access to a shared resource:

  • First, you acquire the semaphore, with the acquire() method.
  • Then, you do the necessary operations with the shared resource.
  • Finally, release the semaphore with the release() method.

场景:

假设一个服务器资源有限,任意某一时刻只允许3个人同时访问,这时一共来了10个人

package com.test;import java.util.concurrent.Semaphore;public class SemaphoreDemo{  public static void main(String args[]) throws Exception{    final Semaphore semaphore = new Semaphore(3);//一次只允许3个人进行访问    for(int i=0;i<10;i++) {   final int no = i;   Runnable thread = new Runnable() {    public void run (){     try {      System.out.println("用户"+no+"连接上了:");      Thread.sleep(300L);      semaphore.acquire();//获取执行的许可      System.out.println("用户"+no+"开始访问后台程序...");      Thread.sleep(1000L);//模仿用户访问服务过程      semaphore.release();//释放,允许下一个线程访问后台      System.out.println("用户"+no+"访问结束。");     } catch (InterruptedException e) {      e.printStackTrace();     }    }   };   new Thread(thread).start();  }    System.out.println("Main thread end!"); }}

 

上述代码运行结果如下:

用户1连接上了:用户3连接上了:用户4连接上了:用户2连接上了:用户0连接上了:用户5连接上了:用户7连接上了:Main thread end!用户6连接上了:用户8连接上了:用户9连接上了:用户3开始访问后台程序...用户4开始访问后台程序...用户2开始访问后台程序...用户4访问结束。用户3访问结束。用户7开始访问后台程序...用户0开始访问后台程序...用户8开始访问后台程序...用户2访问结束。用户5开始访问后台程序...用户0访问结束。用户7访问结束。用户1开始访问后台程序...用户8访问结束。用户6开始访问后台程序...用户1访问结束。用户9开始访问后台程序...用户5访问结束。用户6访问结束。用户9访问结束。

从结果上可以看出来,10个人同时进来,但是只能同时3个人访问资源,释放一个允许进来一个

Note:

When a thread......

原文转载:http://www.shaoqun.com/a/862382.html

跨境电商:https://www.ikjzd.com/

ebay易趣:https://www.ikjzd.com/w/210

yiqu:https://www.ikjzd.com/w/210

亚马逊礼品卡:https://www.ikjzd.com/w/1090.html


一、初识Semaphore小结:A、可以将信号量可视化为一个计数器,它可以递增或递减。B、从概念上讲,信号量维护了一个许可集合,Semaphore对可用的许可进行计数。C、当计数器的值为0时,它能够使线程等待。二、示例Thethreestepsyoumustfollowwhenyouuseasemaphoretoimplementacriticalsectionandprotecttheacces
ad公司:https://www.ikjzd.com/w/1332
行业十字路口!亚马逊测评美亚站点高风控,方向该如何选择?:https://www.ikjzd.com/articles/133235
智利举办"网络星期一"线上促销 商家商品折扣高达70%:https://www.ikjzd.com/articles/133234
如何避免产品安全性问题:https://www.ikjzd.com/articles/133233
美国大选"僵持不下",中国卖家却在亚马逊上演"宫斗"大戏...:https://www.ikjzd.com/articles/133232
我被外国黑人3p过程 太粗太长弄死了我了:http://lady.shaoqun.com/a/256971.html
快递员坚硬粗大 快递员弄得我嗷嗷叫爽:http://lady.shaoqun.com/a/247226.html
男人爱㖭女人下边 被㖭下面是什么感觉:http://www.30bags.com/m/a/249751.html
官员去外地不允许带老婆。如何解决他们的生理需求?:http://lady.shaoqun.com/a/412987.html
轻松解决大多数人不知道的"生理需求"的五种方法:http://lady.shaoqun.com/a/412988.html
武汉13所寄宿制学校的住宿条件和费用被充分曝光:http://lady.shaoqun.com/a/412989.html
异地恋,如何解决生理需求?:http://lady.shaoqun.com/a/412991.html

No comments:

Post a Comment