c#多线程 使用lock锁

使用 lock 关键字可以确保在同一时刻只有一个线程可以访问被锁定的代码块,从而避免线程资源竞争。以下是修改后的示例代码:

csharp 复制代码
using System;
using System.Threading;

class Program
{
    static int sharedNumber = 0;
    static int iterations = 1000000;
    static object lockObject = new object();

    static void Main(string[] args)
    {
        Thread thread1 = new Thread(Increment);
        Thread thread2 = new Thread(Increment);

        thread1.Start();
        thread2.Start();
        //等待线程执行完毕(不加join结果可能会不一样)
        thread1.Join();
        thread2.Join();

        Console.WriteLine("Final shared number: " + sharedNumber);
    }

    static void Increment()
    {
        for (int i = 0; i < iterations; i++)
        {
            lock (lockObject)
            {
                sharedNumber++;
            }
        }
    }
}

在这个示例中,我们使用 lock 关键字来锁定对 sharedNumber 的访问。这样,只有一个线程可以同时访问 sharedNumber,从而避免了线程资源竞争,确保了正确的递增操作。

相关推荐
Kelvin_Ngan2 小时前
C#从XmlDocument提取完整字符串
c#
iqay4 小时前
【C语言】填空题/程序填空题1
c语言·开发语言·数据结构·c++·算法·c#
中游鱼11 小时前
C# 数组和列表的基本知识及 LINQ 查询
c#·linq·数组·数据处理·list数列
32码奴12 小时前
C#基础知识
开发语言·c#
来恩100321 小时前
C# 类与对象详解
开发语言·c#
Dr.勿忘1 天前
C#面试常考随笔8:using关键字有哪些用法?
开发语言·unity·面试·c#·游戏引擎
xcLeigh1 天前
WPF进阶 | WPF 数据绑定进阶:绑定模式、转换器与验证
c#·wpf
谢大旭1 天前
ASP.NET Core 中间件
后端·中间件·c#
时光追逐者1 天前
Visual Studio使用GitHub Copilot提高.NET开发工作效率
c#·github·.net·copilot·ai编程·微软技术·visual studio
唐青枫1 天前
dotnet LINQ 使用简明教程
c#·.net