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
线程。