首页主机资讯c# wait 与 notifyAll 怎样用

c# wait 与 notifyAll 怎样用

时间2025-09-27 03:05:03发布访客分类主机资讯浏览956
导读:在C#中,Wait和NotifyAll是用于线程同步的方法,它们主要用于协调多个线程之间的操作。这两个方法通常在多线程编程中使用,以确保在某个条件满足之前,线程会等待,直到其他线程改变了共享资源的状态。 Wait方法用于让当前线程等待,直到...

在C#中,WaitNotifyAll是用于线程同步的方法,它们主要用于协调多个线程之间的操作。这两个方法通常在多线程编程中使用,以确保在某个条件满足之前,线程会等待,直到其他线程改变了共享资源的状态。

Wait方法用于让当前线程等待,直到另一个线程调用同一对象的NotifyAll方法或Notify方法。NotifyAll方法会唤醒所有等待该对象的线程,而Notify方法只会唤醒一个等待该对象的线程。

下面是一个简单的示例,展示了如何使用WaitNotifyAll方法:

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++;

        }

    }

}
    

在这个示例中,我们有两个线程Thread1Thread2。它们都尝试访问共享资源sharedResource,但在访问之前,它们需要等待某个条件满足。为了实现这一点,我们使用了一个锁对象lockObject,并在访问共享资源之前调用Monitor.Wait(lockObject)方法。当另一个线程改变共享资源的状态时,它将调用Monitor.NotifyAll(lockObject)方法来唤醒所有等待的线程。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: c# wait 与 notifyAll 怎样用
本文地址: https://pptw.com/jishu/709391.html
c# wait 对线程状态有何影响 c# wait 能设置超时时间吗

游客 回复需填写必要信息