using System;
using System.Threading;
class Program
{
// 定义一个互斥体,用于同步多个线程对共享资源的访问
private static Mutex mutex = new Mutex();
static void Main()
{
// 创建两个线程来模拟并发访问
Thread thread1 = new Thread(WriteToConsole);
Thread thread2 = new Thread(WriteToConsole);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
}
static void WriteToConsole()
{
// 尝试获取互斥体锁
mutex.WaitOne();
// 打印当前线程的名称和ID
Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} is writing to the console.");
// 模拟一些耗时操作
Thread.Sleep(1000);
// 释放互斥体锁
mutex.ReleaseMutex();
}
}
mutex.WaitOne():尝试获取互斥体锁。如果锁已被其他线程持有,则当前线程会阻塞,直到锁被释放。mutex.ReleaseMutex():释放互斥体锁,允许其他等待的线程获取锁。上一篇:c# intptr
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站