c#中类似java的wait和notify的机制

cs 复制代码
using System;
using System.Threading;
 
public class Program
{
    private static object _lockObject = new object();
    private static bool _condition = false;
 
    public static void Main()
    {
        Thread producerThread = new Thread(new ThreadStart(Producer));
        Thread consumerThread = new Thread(new ThreadStart(Consumer));
 
        producerThread.Start();
        consumerThread.Start();
 
        producerThread.Join();
        consumerThread.Join();
    }
 
    private static void Producer()
    {
        lock (_lockObject)
        {
            Console.WriteLine("Producer: Waiting for condition to become true...");
            while (!_condition)
            {
                Monitor.Wait(_lockObject);
            }
            Console.WriteLine("Producer: Condition is true, doing some work...");
            // ... do some work ...
        }
    }
 
    private static void Consumer()
    {
        // Wait a bit to ensure the producer thread has started and is waiting
        Thread.Sleep(1000);
 
        lock (_lockObject)
        {
            _condition = true;
            Console.WriteLine("Consumer: Setting condition to true, notifying producer...");
            Monitor.Pulse(_lockObject);
        }
    }
}

c# 有没有java中wait 和 notify机制

在C#中,没有直接的waitnotify机制,但你可以使用Monitor类来实现类似的功能。Monitor类提供了Wait方法,这类似于Java中的wait方法,它会释放当前对象的锁,并使当前线程等待。同时,Monitor类也提供了PulsePulseAll方法,这类似于Java中的notifynotifyAll方法,它会唤醒等待队列中的一个或所有线程。

在这个例子中,Producer方法在一个同步块中等待一个条件变为真,而Consumer方法则设置这个条件为真并通知等待的线程。Monitor.Wait方法使得Producer线程进入等待状态,并释放了锁,而Monitor.Pulse方法则唤醒等待中的Producer线程。

java中wait和notify的作用

相关推荐
雨落倾城夏未凉2 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫3 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫4 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6254 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902114 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠5 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫7 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech7 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf9 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6259 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#