using System;
using System.Threading;
class Program
{
private static readonly object lockObject = new object();
private static int counter = 0;
static void Main()
{
Thread thread1 = new Thread(IncrementCounter);
Thread thread2 = new Thread(IncrementCounter);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.WriteLine("Final counter value: " + counter);
}
static void IncrementCounter()
{
for (int i = 0; i < 1000; i++)
{
// 使用锁确保同一时间只有一个线程可以访问 critical section
lock (lockObject)
{
int temp = counter;
Thread.Sleep(0); // 模拟一些工作
counter = temp + 1;
}
}
}
}
lockObject: 用于锁定的对象。在多线程环境中,通过 lock 关键字来确保同一时间只有一个线程可以访问被锁定的代码段(即临界区)。
counter: 一个共享变量,两个线程会同时对其进行递增操作。如果没有加锁,可能会出现竞态条件(race condition),导致最终结果不正确。
IncrementCounter 方法: 每个线程执行该方法,尝试对 counter 进行递增。lock 确保每次只有一个线程能够进入临界区,从而避免了竞态条件。
Thread.Sleep(0): 模拟一些耗时操作,增加并发问题的可能性,以便更好地展示锁的作用。
thread1.Join() 和 thread2.Join(): 主线程等待两个子线程完成后再继续执行,确保输出的是最终的结果。
通过这种方式,可以确保多个线程安全地访问和修改共享资源。
上一篇:c#打开文件夹
下一篇:c# 四舍五入取整数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站