当前位置: 首页 > news >正文

关于线程的例子

下面是两个线程,每个线程循环10000次,结果应该是20000,运行一下程序,是不是想要的结果

public static void Main(string[] args)
{var thread1 = new System.Threading.Thread(ThreadMethod);var thread2 = new System.Threading.Thread(ThreadMethod);thread1.Start();thread2.Start();thread1.Join();thread2.Join();Debug.WriteLine($"Count: {count}");Console.ReadLine();
}static int count = 0;
static int total = 10000;
static void ThreadMethod()
{for (int i = 0; i < total; i++){count++;}
}

运行后结果总是1w多点,而不是2W,
下面给出2中解决方案
第一种是用lock

    public static void Main(string[] args){var thread1 = new System.Threading.Thread(ThreadMethod);var thread2 = new System.Threading.Thread(ThreadMethod);thread1.Start();thread2.Start();thread1.Join();thread2.Join();Debug.WriteLine($"Count: {count}");Console.ReadLine();}static int count = 0;static int total = 10000;private static object m_obj = new object();static void ThreadMethod(){for (int i = 0; i < total; i++){lock (m_obj){count++;}}}

第二种,直接用.ne提供的框架中的Interlocked

    public static void Main(string[] args){var thread1 = new System.Threading.Thread(ThreadMethod);var thread2 = new System.Threading.Thread(ThreadMethod);thread1.Start();thread2.Start();thread1.Join();thread2.Join();Debug.WriteLine($"Count: {count}");Console.ReadLine();}static int count = 0;static int total = 10000;static void ThreadMethod(){for (int i = 0; i < total; i++){Interlocked.Increment(ref count);}}
http://www.lryc.cn/news/595449.html

相关文章:

  • 【力扣】第42题:接雨水
  • 复制docker根目录遇到的权限问题
  • 模拟高负载测试脚本
  • 闲庭信步使用图像验证平台加速FPGA的开发:第二十八课——图像膨胀的FPGA实现
  • 关于Ajax的学习笔记
  • Linux的相关指令
  • 「日拱一码」034 机器学习——插值处理
  • Unity 脚本生命周期详解与实战分析
  • (十九)深入了解 AVFoundation-编辑:使用 AVMutableVideoComposition 实现视频加水印与图层合成(上)——理论篇
  • iOS 加固工具有哪些?快速发布团队的实战方案
  • RIQ模型时间管理方法详解
  • 工业自动化中的协议转换:RS485转PROFIBUS网关在涡街流量计与S7-300 PLC通信中的应用
  • Swap Face 使用遇到的问题
  • Match宣布2025曼谷发布会,发布“保本”资管新范式,旨在重塑Web3投资规则
  • 20250720问答课题-基于BERT与混合检索问答系统代码解读
  • 企业开发转型 | 前端AI化数字化自动化现状
  • 自动化商品监控:利用淘宝API开发实时价格库存采集接口
  • 【unitrix】 6.11 二进制数字标准化模块(normalize.rs)
  • G7打卡——Semi-Supervised GAN
  • Acrobat JavaScript 中的 `app.response()` 方法
  • 【学习路线】C#企业级开发之路:从基础语法到云原生应用
  • 基于MySQL实现分布式调度系统的选举算法
  • 一文速通《矩阵的特征值和特征向量》
  • Tomcat的部署、单体架构、session会话、spring
  • PostgreSQL高可用架构Repmgr部署流程
  • 计算机网络中:传输层和网络层之间是如何配合的
  • socket编程(UDP)
  • vue2使用v-viewer图片预览:打开页面自动预览,禁止关闭预览,解决在微信浏览器的页面点击事件老是触发预览初始化的问题
  • Linux 721 创建实现镜像的逻辑卷
  • 网络数据分层封装与解封过程的详细说明