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

相关推荐
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ4 小时前
通过java后端代码来实现给word内容补充格式文本内容控件,以及 设置控件的标记和标题
java·c#·word
Hesionberger10 小时前
LeetCode79:单词搜索DFS回溯详解
java·开发语言·c++·python·算法·leetcode·c#
曹牧12 小时前
C#:同一项目中维护多个版本的代码
开发语言·c#
工程师00712 小时前
C# UI 跨线程刷新:Invoke/BeginInvoke 原理与封装
c#·invoke·begininvoke
码农刚子14 小时前
.NET 8 Web开发入门(二):C# 现代语法速成——为 Web API 量身定制
c#·.net
江沉晚呤时15 小时前
用 C# 玩转 Scriban:自动生成报告、代码、文本,效率提升 10 倍
数据库·microsoft·c#·.net
hixiong1231 天前
C# TensorRT部署RF-DETR目标检测&分割模型
人工智能·目标检测·计算机视觉·ai·c#
神仙别闹1 天前
基于C# 利用工程活动图 AOE 网设计算法
算法·c#·php
游乐码1 天前
c#迭代器
开发语言·c#