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#中,没有直接的wait和notify机制,但你可以使用Monitor类来实现类似的功能。Monitor类提供了Wait方法,这类似于Java中的wait方法,它会释放当前对象的锁,并使当前线程等待。同时,Monitor类也提供了Pulse或PulseAll方法,这类似于Java中的notify或notifyAll方法,它会唤醒等待队列中的一个或所有线程。

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

java中wait和notify的作用

相关推荐
吾与谁归in6 小时前
C#脚本工具,支持智能提示自动补全(WPF + Roslyn + AvalonEdit)
开发语言·c#·wpf
昂好的day7 小时前
WPF 从零入门(上):WPF 是什么、XAML 语法、布局与样式全解
开发语言·c#·wpf
吃一碗粉只付一碗钱1 天前
10-令牌里的用户主键不要明文
服务器·数据库·sql·sqlserver·c#
胖纸不争1 天前
EnergyStarZ:让 Windows 后台进程给前台让路的能效管理器(v1.2 发布)
windows·性能优化·c#·win32·ef core
曹牧1 天前
C#:The operation has timed out
开发语言·c#
He BianGu1 天前
【WPF-Control教程】IOC 依赖注入
c#·wpf·wpf-control
He BianGu1 天前
【WPF-Control教程】H.Extensions.Behvaiors 开发文档
c#·wpf·wpf-control
He BianGu1 天前
【WPF-Control教程】H.Style 开发文档
c#·wpf·wpf-control
He BianGu1 天前
【WPF-Control教程】MVVM 二次开发文档
c#·wpf·wpf-control