zoukankan
html css js c++ java
应用程序中的所有线程都可以访问方法中的公用字段。要同步对公用字段的访问,您可以使用属性替代字段,并使用 ReaderWriterLock 对象控制访问。为此,请按照下列步骤操作:
using
System;
using
System.Threading;
namespace
MultiThreadApplication
{
class
Class1
{
private
ReaderWriterLock rwl
=
new
ReaderWriterLock();
private
long
myNumber;
public
long
Number
//
the Number property
{
get
{
//
Acquire a read lock on the resource.
rwl.AcquireReaderLock(Timeout.Infinite);
try
{
Console.WriteLine(
"
Thread:{0} starts getting the Number
"
, Thread.CurrentThread.GetHashCode());
Thread.Sleep(
50
);
Console.WriteLine(
"
Thread:{0} got the Number
"
, Thread.CurrentThread.GetHashCode());
}
finally
{
//
Release the lock.
rwl.ReleaseReaderLock();
}
return
myNumber;
}
set
{
//
Acquire a write lock on the resource.
rwl.AcquireWriterLock(Timeout.Infinite);
try
{
Console.WriteLine(
"
Thread: {0} start writing the Number
"
, Thread.CurrentThread.GetHashCode());
Thread.Sleep(
50
);
myNumber
=
value;
Console.WriteLine(
"
Thread: {0} written the Number
"
, Thread.CurrentThread.GetHashCode());
}
finally
{
//
Release the lock.
rwl.ReleaseWriterLock();
}
}
}
[STAThread]
static
void
Main(
string
[] args)
{
Thread[] threadArray
=
new
Thread[
20
];
int
threadNum;
Class1 Myclass
=
new
Class1();
ThreadStart myThreadStart
=
new
ThreadStart(Myclass.AccessGlobalResource);
//
Create 20 threads.
for
(threadNum
=
0
; threadNum
<
20
; threadNum
++
)
{
threadArray[threadNum]
=
new
Thread(myThreadStart);
}
//
Start the threads.
for
(threadNum
=
0
; threadNum
<
20
; threadNum
++
)
{
threadArray[threadNum].Start();
}
//
Wait until all the thread spawn out finish.
for
(threadNum
=
0
; threadNum
<
20
; threadNum
++
)
threadArray[threadNum].Join();
Console.WriteLine(
"
All operations have completed. Press enter to exit
"
);
Console.ReadLine();
}
public
void
AccessGlobalResource()
{
Random rnd
=
new
Random();
long
theNumber;
if
(rnd.Next()
%
2
!=
0
)
theNumber
=
Number;
else
{
theNumber
=
rnd.Next();
Number
=
theNumber;
}
}
}
}
说明了读写共享资源访问是不冲图的,如下图所示(这个方式解决了多个线程可同时读,只有一个线程可以定的操作的协调)
查看全文
相关阅读:
drf请求生命周期
正向代理和反向代理
cbv源码分析
Python搭建调用本地dll的Windows服务(浏览器可以访问,附测试dll64位和32位文件)
Python实现聊天机器人接口封装部署
Python实现机器人语音聊天
Python爬虫下载美女图片(不同网站不同方法)
微信小程序-点餐系统
Win10系统Python3.8的升级与安装
Python破解Wifi密码思路
原文地址:https://www.cnblogs.com/snowball/p/388282.html
最新文章
js中 a : function(){}这是什么格式? 代表什么含义?怎样学习这样的格式?
ASP.NET 无法生成临时类(result=1)图解
Indenting source code
各种编码问题
How To Configure Logging And Log Rotation In Apache On An Ubuntu VPS
网络tcp/ip资料
Apache指南:CGI动态页面
Windows 7/8 64位下安装64位Apache 2.4.7
c++class 内存布局
c/c++中typedef详解
热门文章
classpath、path、JAVA_HOME的作用及JAVA环境变量配置
计算image 积分图
腾讯2015校招笔试题
rabbitmq
Redis与Mysql双写一致性方案解析
nginx负载均衡?
后台处理跨域
django 中间件
django redis
django缓存机制
Copyright © 2011-2022 走看看