在C#中,Wait和NotifyAll是用于线程同步的方法,它们主要用于协调多个线程之间的操作。这两个方法通常在多线程编程中使用,以确保在某个条件满足之前,线程会等待,直到其他线程改变了共享资源的状态。
Wait方法用于让当前线程等待,直到另一个线程调用同一对象的NotifyAll方法或Notify方法。NotifyAll方法会唤醒所有等待该对象的线程,而Notify方法只会唤醒一个等待该对象的线程。
下面是一个简单的示例,展示了如何使用Wait和NotifyAll方法:
using System;
using System.Threading;
class Program
{
static object lockObject = new object();
static int sharedResource = 0;
static void Main(string[] args)
{
Thread thread1 = new Thread(Thread1);
Thread thread2 = new Thread(Thread2);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
}
static void Thread1()
{
lock (lockObject)
{
Console.WriteLine("Thread 1: Waiting for the condition...");
Monitor.Wait(lockObject);
Console.WriteLine("Thread 1: The condition is met. Accessing the shared resource.");
sharedResource++;
}
}
static void Thread2()
{
lock (lockObject)
{
Console.WriteLine("Thread 2: Waiting for the condition...");
Monitor.Wait(lockObject);
Console.WriteLine("Thread 2: The condition is met. Accessing the shared resource.");
sharedResource++;
}
}
}
在这个示例中,我们有两个线程Thread1和Thread2。它们都尝试访问共享资源sharedResource,但在访问之前,它们需要等待某个条件满足。为了实现这一点,我们使用了一个锁对象lockObject,并在访问共享资源之前调用Monitor.Wait(lockObject)方法。当另一个线程改变共享资源的状态时,它将调用Monitor.NotifyAll(lockObject)方法来唤醒所有等待的线程。