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

相关推荐
William_cl6 小时前
一、前置基础(MVC学习前提)_核心特性_【C# 泛型入门】为什么说 List<T>是程序员的 “万能收纳盒“?避坑指南在此
学习·c#·mvc
c#上位机10 小时前
wpf之命令
c#·wpf
曹牧13 小时前
C#:函数默认参数
开发语言·c#
R-G-B1 天前
【02】C#入门到精通——C# 变量、输入/输出、类型转换
开发语言·c#·c# 变量·c#输入/输出·c#类型转换
星河队长1 天前
C# 软件加密方法,有使用时间限制,同时要防止拷贝
开发语言·c#
Aevget1 天前
DevExpress WinForms v25.1亮点 - PDF Viewer(查看器)等全新升级
pdf·c#·界面控件·winform·devexpress·ui开发
InCerry1 天前
为 .NET 10 GC(DATAS)做准备
性能优化·c#·.net·gc
曹牧1 天前
C#:可选参数
开发语言·c#
Sunsets_Red1 天前
差分操作正确性证明
java·c语言·c++·python·算法·c#
Aevget1 天前
DevExpress WPF中文教程:Data Grid - 如何使用虚拟源?(一)
c#·wpf·界面控件·devexpress·ui开发