c# wait 与 notify 怎样配合
导读:在C#中,Wait和Notify通常用于线程同步,它们是Object类中的两个方法。Wait方法会使当前线程等待,直到另一个线程调用同一对象的Notify或NotifyAll方法。这两个方法通常在多线程环境中使用,以避免资源竞争和数据不一致...
在C#中,Wait
和Notify
通常用于线程同步,它们是Object
类中的两个方法。Wait
方法会使当前线程等待,直到另一个线程调用同一对象的Notify
或NotifyAll
方法。这两个方法通常在多线程环境中使用,以避免资源竞争和数据不一致。
以下是一个简单的示例,说明如何使用Wait
和Notify
方法:
using System;
using System.Threading;
class Program
{
static object lockObject = new object();
static int sharedResource = 0;
static void Main(string[] args)
{
Thread t1 = new Thread(ThreadMethod1);
Thread t2 = new Thread(ThreadMethod2);
t1.Start();
t2.Start();
t1.Join();
t2.Join();
}
static void ThreadMethod1()
{
lock (lockObject)
{
Console.WriteLine("Thread 1: Waiting for resource...");
Monitor.Wait(lockObject);
Console.WriteLine("Thread 1: Resource acquired.");
sharedResource++;
Console.WriteLine($"Thread 1: Shared resource value: {
sharedResource}
");
Monitor.Notify();
}
}
static void ThreadMethod2()
{
lock (lockObject)
{
Console.WriteLine("Thread 2: Waiting for resource...");
Monitor.Wait(lockObject);
Console.WriteLine("Thread 2: Resource acquired.");
sharedResource--;
Console.WriteLine($"Thread 2: Shared resource value: {
sharedResource}
");
Monitor.Notify();
}
}
}
在这个示例中,我们有两个线程ThreadMethod1
和ThreadMethod2
。它们都尝试访问共享资源sharedResource
。为了避免数据不一致,我们使用lockObject
对象来同步线程。当一个线程获得锁并访问共享资源时,其他线程必须等待,直到锁被释放。
Monitor.Wait(lockObject)
方法使当前线程等待,直到另一个线程调用Monitor.Notify(lockObject)
或Monitor.NotifyAll(lockObject)
方法。在这个例子中,我们使用Monitor.Notify()
方法唤醒一个等待的线程。当一个线程被唤醒并重新获得锁时,它将能够访问共享资源。
注意:在实际应用中,通常建议使用Monitor.Wait()
和Monitor.NotifyAll()
而不是Thread.Wait()
和Thread.Notify()
,因为它们提供了更好的封装和错误处理。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c# wait 与 notify 怎样配合
本文地址: https://pptw.com/jishu/709404.html