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的作用

相关推荐
gregmankiw2 小时前
C#调用Rust动态链接库DLL的案例
开发语言·rust·c#
阿蒙Amon3 小时前
06. C#入门系列【自定义类型】:从青铜到王者的进阶之路
开发语言·c#
钢铁男儿6 小时前
C# 表达式和运算符(表达式和字面量)
开发语言·c#
林鸿群7 小时前
C#子线程更新主线程UI及委托回调使用示例
开发语言·c#
o0向阳而生0o7 小时前
63、.NET 异常处理
c#·.net·异常处理
SteveDraw9 小时前
C++动态链接库封装,供C#/C++ 等编程语言使用——C++动态链接库概述(总)
开发语言·c++·c#·封装·动态链接库
Kookoos10 小时前
性能剖析:在 ABP 框架中集成 MiniProfiler 实现性能可视化诊断
后端·c#·.net·abp vnext·miniprofiler
阿翰12 小时前
自动 GitHub Readme 20 种语言翻译平台 - OpenAiTx 开源免费
c#·.net
枫叶kx16 小时前
1Panel运行的.net程序无法读取系统字体(因为使用了docker)
c#
军训猫猫头21 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#