System.Threading.Monitor

System.Threading.Monitor

 


using  System;
using  System.Threading;
using  System.Collections;

namespace  OracleTest
{
    
class MonitorSample
    
{
        
const int MAX_LOOP_TIME = 1000;
        Queue    m_smplQueue;

        
public MonitorSample()
        
{
            m_smplQueue 
= new Queue();
        }

        
        
public void FirstThread()
        
{
            
int counter = 0;
            
            
lock(m_smplQueue)
            
{
                
while(counter < MAX_LOOP_TIME)
                
{
                    
//Wait, if the queue is busy.
                    Monitor.Wait(m_smplQueue);
                    
//Push one element.
                    m_smplQueue.Enqueue(counter);
                    
//Release the waiting thread.
                    Monitor.Pulse(m_smplQueue); 
                    counter
++;
                }

            }

        }

        
        
public void SecondThread()
        
{
            
lock(m_smplQueue)
            
{
                
//Release the waiting thread.
                Monitor.Pulse(m_smplQueue);
                
//Wait in the loop, while the queue is busy.
                
//Exit on the time-out when the first thread stops.
                while(Monitor.Wait(m_smplQueue,1000))
                
{
                    
//Pop the first element.
                    int counter = (int)m_smplQueue.Dequeue();
                    
//Print the first element.
                    Console.WriteLine(counter.ToString());
                    
//Release the waiting thread.
                    Monitor.Pulse(m_smplQueue);
                }

            }

        }

        
        
//Return the number of queue elements.
        public int GetQueueCount()
        
{
            
return m_smplQueue.Count;
        }

        
        
static void Main(string[] args)    
        
{
            
//Create the MonitorSample object.
            MonitorSample test = new MonitorSample(); 
            
//Create the first thread.
            Thread tFirst = new Thread(new ThreadStart(test.FirstThread));
            
//Create the second thread.
            Thread tSecond = new Thread(new ThreadStart(test.SecondThread));
            
//Start threads.
            tFirst.Start();
            tSecond.Start();
            
//wait to the end of the two threads
            tFirst.Join();
            tSecond.Join();
            
//Print the number of queue elements.
            Console.WriteLine("Queue Count = " + test.GetQueueCount().ToString());
            Console.ReadLine();
        }

    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值