boundedbuffer.cs

来自「jsp+javabean+servlet实现的在线书店」· CS 代码 · 共 66 行

CS
66
字号
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace IM
{
    public class BoundedBuffer
    {
        const int BufferSize = 10;
        object synchObject = new object();
        AutoResetEvent notFull=new AutoResetEvent(false);
        AutoResetEvent notEmpty=new AutoResetEvent(false);
        object[] buffer = new object[BufferSize];
        int putPoint=0, takePoint=0,count=0;
        public void put(object o)
        {
            bool full = false;            
            lock (synchObject)
            {
                if (count == BufferSize)
                    full = true;
                Console.WriteLine("put: count="+count);
            }
            if (full)
            {
                Console.WriteLine("put: waiting for notFull ...");
                notFull.WaitOne();
                Console.WriteLine("put: get notFull signal ...");
            }
            lock (synchObject)
            {
                count++;
                buffer[putPoint] = o;
                putPoint = (putPoint + 1) % BufferSize;
            }
            notEmpty.Set();
        }
        public object take()
        {
            bool empty = false;
            lock (synchObject)
            {
                if (count == 0)
                    empty = true;
                Console.WriteLine("take: count=" + count);
            }
            if (empty)
            {
                Console.WriteLine("take: waiting for notEmpty ...");
                notEmpty.WaitOne();
                Console.WriteLine("take: get notEmpty signal ...");
            }
            object result;
            lock (synchObject)
            {
                count--;
                result = buffer[takePoint];
                takePoint = (takePoint + 1) % BufferSize;
            }
            notFull.Set();
            return result;
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?