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;
}
}
}
}
说明了读写共享资源访问是不冲图的,如下图所示(这个方式解决了多个线程可同时读,只有一个线程可以定的操作的协调)
查看全文
相关阅读:
设置toad for oracle命令行自动补全
toad安装oracle客户端过程
如何设置oracle表空间自动扩展
centos7平台安装python3
oracle监听报The listener supports no services
各平台下oracle-instant-client安装部署
Oracle工具(Oracle Tools) – RDA(RemoteDiagnostic Agent)
centOS7下安装GUI图形界面
Linux 系统健康巡检脚本
oracle 巡检脚本(自动化)
原文地址:https://www.cnblogs.com/snowball/p/388282.html
最新文章
Linux修改系统时间
node.js 热更新 自动重新编译 配置记录
深入Node.js 模块机制
MongoDB 安装教程
Windows下RabbitMQ安装及配置简易教程
生成UML图的工具 安装教程
无法启动此程序,因为计算机中丢失MSVCR120.dll 解决
windows下安装 redis 教程
mysql 5.7 压缩包安装教程
下拉插件 (带搜索) Bootstrap-select 从后台获取数据填充到select的 option中 用法详解
热门文章
Mysql 转 Sql Server的一些问题总结
加密算法(DES,AES,RSA,MD5,SHA1,Base64)比较和项目应用
UTF-8和GBK编码之间的区别(页面编码、数据库编码区别)以及在实际项目中的应用
网站常见的入侵手段和防御方法
SQL通用优化方案(where优化、索引优化、分页优化、事务优化、临时表优化)
分布式、高并发、高性能场景(抢购、秒杀、抢票、限时竞答)数据一致性解决方案
SQL Server参数化SQL语句中的like和in查询的语法(C#)
开放接口/RESTful/Api服务的设计和安全方案
SQL注入(SQL Injection)案例和防御方案
XSS/CSRF跨站攻击和防护方案
Copyright © 2011-2022 走看看