Multi-threaded execution methods cannot call the secondary method when the method is not finished executing.
It takes a minute to execute a method in a loop, and no member can call the method again within a minute.
classMonitorsample {Private intn =1;//data that producers and consumers work together Private intMax =10000; Private ObjectMonitor =New Object(); Public voidProduce () {Lock(monitor) { for(; n <= Max; n++) {Console.WriteLine ("Mom: No."+ n.tostring () +"a piece of cake is ready."); //The pulse method is not called because the Wait (Object,int) method is used in another thread//This method causes the blocked thread to enter the ready queue of the synchronization object//whether pulse activation is required is an important difference between one parameter and two parameters of the wait method//Monitor.pulse (Monitor); //call the Wait method to release the lock on the object and block the thread (thread state is WaitSleepJoin)//the thread enters the wait queue for the synchronization object until another thread calls pulse to get the thread into the ready queue//The thread enters the ready queue to compete for ownership of the synchronization object//if no other thread calls the Pulse/pulseall method, the thread cannot be executedmonitor.wait (Monitor); } } } Public voidconsume () {Lock(monitor) { while(true) { //notifies a thread in the wait queue to lock changes to the state of an object, but does not release the lock//when a pulse pulse is received, the thread moves from the waiting queue of the synchronization object to the ready queue//Note: The thread that eventually gets the lock is not necessarily the thread that gets the pulse pulsesMonitor.pulse (Monitor); //releases the lock on the object and blocks the current thread until it acquires the lock again//If the specified time-out interval has elapsed, the thread enters the ready queueMonitor.Wait (monitor, +); Console.WriteLine ("Child: Start eating first"+ n.tostring () +"Block Cake"); } } } Static voidMain (string[] args) {Monitorsample obj=Newmonitorsample (); Thread Tproduce=NewThread (NewThreadStart (obj. produce)); Thread Tconsume=NewThread (NewThreadStart (obj. consume)); //Start threads.Tproduce.start (); Tconsume.start (); Console.ReadLine (); } }
The basic method of monitor is that pulse and wait,pulse are release locks, wait is accepted and wait, with lock use can easily realize the multi-threading problem of producer and consumer.
C # Multithreading Limit Method Invocation (monitor)