一、简介

Semaphore类限制可同时访问某一资源或资源池的线程数。线程通过调用 WaitOne方法将信号量减1,并通过调用 Release方法把信号量加1。

构造函数:public Semaphore(int initialCount,int maximumCount);通过两个参数来设置信号的初始计数和最大计数。

二、例子

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading;
6 using System.Threading.Tasks;
7
8 namespace ThreadMutex
9 {
10 class Program
11 {
12 private static Mutex mutex = new Mutex();
13 private static Semaphore semaphore = new Semaphore(3, 10);
14 private static int sum = 0;
15 static void Main(string[] args)
16 {
17 for (int i = 0; i < 10; i++)
18 {
19 Task<int> task = new Task<int>(ThreadFunction);
20 task.Start();
21 }
22 Console.WriteLine($"{DateTime.Now} task started!");
23 Console.Read();
24
25 }
26 private static int ThreadFunction()
27 {
28 Thread.Sleep(100);
29 if(semaphore.WaitOne(2000))
30 {
31 Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} get semaphore successed!");
32 }
33 else
34 {
35 Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} get semaphore failed!");
36 }
37
38 return sum;
39 }
40 }
41 }

运行结果如下:

最新文章

  1. Hihocoder 1079 离散化
  2. shutdown
  3. Idea15/16 配置Tomcat
  4. sbt %%
  5. bootstrap插件学习-bootstrap.alert.js
  6. python scrapy 获取华为应用市场APP评论数据
  7. 【Toolkit】关闭Closeable的简单工具类
  8. javaSE之如何将一个文档显示出来(,txt,.doc,.....)
  9. slowhttps安装及使用心得
  10. 微软职位内部推荐-Enterprise Architect - BDE - BJ
  11. spserver 开源服务器框架研究与分析
  12. ReactNative布局样式总结
  13. AtCoder Beginner Contest 069【A,水,B,水,C,数学,D,暴力】
  14. awk的sub函数和gsub函数的用法
  15. HI3531由DMA 发起PCIe 事务
  16. Java核心技术卷一基础知识-第7章-图形程序设计-读书笔记
  17. windows中dir命令
  18. leetcode46
  19. 《GPU高性能编程CUDA实战》第四章 简单的线程块并行
  20. C语言扫盲篇

热门文章

  1. C语言中函数的返回值
  2. LeetCode 887. Super Egg Drop
  3. java并发编程基础——线程相关的类
  4. 【转载】PHP 程序员进阶之路
  5. SDN与OpenFlow架构--初识
  6. Vulnhub -- DC2靶机渗透
  7. Python基础之实现界面和代码分离
  8. 构建后端第3篇之---springb @Alias注解使用
  9. PWA渐进式web应用
  10. 【硬核】MMU是如何完成地址翻译的