多线程15-ReaderWriterLockSlim
2024-08-31 10:36:10
class Program
{
static void Main()
{
new Thread(Read) { IsBackground = true }.Start();
new Thread(Read) { IsBackground = true }.Start();
new Thread(Read) { IsBackground = true }.Start();
new Thread(Read) { IsBackground = true }.Start();
new Thread(Read) { IsBackground = true }.Start();
new Thread(() => Write("T1")) { IsBackground = true }.Start();
new Thread(() => Write("T2")) { IsBackground = true }.Start();
Thread.Sleep(TimeSpan.FromSeconds());
}
static ReaderWriterLockSlim rwl = new ReaderWriterLockSlim();
static Dictionary<int, int> items = new Dictionary<int, int>();
static void Read()
{
Console.WriteLine("Readind contents of a dictionary");
while (true)
{
try
{
rwl.EnterReadLock();
foreach (var item in items.Keys)
{
Thread.Sleep(TimeSpan.FromSeconds(0.1));
Console.WriteLine(items[item]);
}
}
finally
{
rwl.ExitReadLock();
}
}
}
static void Write(string threadName)
{
while (true)
{
try
{
int newKey = new Random().Next();
rwl.EnterUpgradeableReadLock();
if (!items.ContainsKey(newKey))
{
try
{
rwl.EnterWriteLock();
items[newKey] = newKey;
Console.WriteLine("New Key {0} is added to a dictionary by a {1}", newKey, threadName);
}
finally
{
rwl.ExitWriteLock();
}
}
Thread.Sleep(TimeSpan.FromSeconds(0.1));
}
finally
{
rwl.ExitUpgradeableReadLock();
}
}
}
}
最新文章
- 《AngularJS深度剖析与最佳实践》简介
- 了解 xcodebuild 命令 ,自动打包ipa
- [python实现设计模式]-2.模板方法模式---把大象关进冰箱.
- bootstrap使用性能问题
- 使用Matrix控制图像或组件变换的步骤
- Ubuntu 12.04.2搭建nfs服务器
- Asp.Net 之 母版页中对控件ID的处理
- .NET/ASP.NET Routing路由(深入解析路由系统架构原理)http://wangqingpei557.blog.51cto.com/1009349/1312422
- 图形用户界面(graphical user interface)
- 三分钟学会CSS3中的FLEXBOX布局
- quartz_spring 定时器配置
- Struts2 03---数据封装+获取表单提交数据
- MysqL主从复制_模式之GTID复制
- 第一个bug
- 【转】Fundebug上线微信小游戏错误监控!支持自动截屏!
- [Swift]LeetCode72. 编辑距离 | Edit Distance
- MATLAB EMD 初始
- Java 并发编程-再谈 AbstractQueuedSynchronizer 2:共享模式与基于 Condition 的等待 / 通知机制实现
- rabbitmq更换数据文件和日志文件的存放位置
- 开发中经常遇到SVN清理失败的问题:
热门文章
- #333 Div2 Problem B Approximating a Constant Range (尺取 &;&; RMQ || 尺取 &;&; multiset)
- 举例子说明ubuntu中remove,autoremove,purge区别
- 更好的构建 Node 服务的工具
- java8 for循环了改为 流
- sqli-labs(26a)
- sqli-labs(25a)
- SVN appears to be part of a Subversion 问题心得
- Python的复制,浅拷贝和深拷贝
- java内存分布详解
- nginx检查报错:nginx: [emerg] ";server"; directive is not allowed here in