在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)方法来唤醒所有等待的线程。
以上就是关于“c# wait 与 notifyAll 怎样用”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm