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;
}
}
}
}
说明了读写共享资源访问是不冲图的,如下图所示(这个方式解决了多个线程可同时读,只有一个线程可以定的操作的协调)
查看全文
相关阅读:
javascript检测浏览器插件
登陆注册数据库设计与任务分配
做网站的一些定律原理和效应
为什么我们应该像盖房子那样写程序?
最近项目中遇到的一些设计问题
反向代理缓存
《你必须知道的.NET》读书笔记
锋利的Jquery读书笔记
将pdf转成jpg格式
《你必须知道的.NET》第五章读书笔记
原文地址:https://www.cnblogs.com/snowball/p/388282.html
最新文章
云计算 学习笔记(3) Google 集群系统 & Hadoop
Lync 2010 标准版 CA证书服务搭建 学习笔记(4)
HTTP:每个Web开发人员必须知道的协议 第2部分
Angular自定义指令下
Angular自定义指令中
controller之间的数据共享(同过factory自定义服务把共享数据传递给各个controller之间)
过滤器filter
css绝对居中的几种方式
Angular自定义指令上
HTTP:每个Web开发人员必须知道的协议 第1部分
热门文章
HTTP状态码
Angular服务
git 克隆 指定分支
子元素 设置margin 会影响父级元素的位置
vue调用后端方法成功获取数据,但页面上拿不到,控制台打印数据是可以打印出来的
centos7 yarn install 装包 报错 deasync: command failed
centos 7 日志清理
IDEA+Gradle+Spring Data mongo 配置 querydsl
盖茨的劝学随想
SqlServer Text类型字段超过8000字处理
Copyright © 2011-2022 走看看