• 蛙蛙推荐:写了一个简单的延迟队列


    写了一个简单的延迟队列,用于处理短时大量请求的情况,可以设置队列处理Handler,每次取队列的时间间隔,以及每次取多少队列项进行处理。

    队列处理是同步执行。

    public class LazyQueue<T>
    {
    public LazyQueue(Action<T> handler, int inteval, int onecount)
    {
    _handler
    = handler;
    _inteval
    = inteval;
    _onecount
    = onecount;
    _t
    = new Thread(ThreadProc);
    _t.Name
    = "LazyQueue";
    _t.IsBackground
    = true;
    }
    public void EnQueue(T item)
    {
    lock (_queue)
    {
    _queue.Enqueue(item);
    }
    }
    public void Start()
    {
    _t.Start();
    }

    private void ThreadProc(object state)
    {
    while (true)
    {
    try
    {
    List
    <T> tempItems = new List<T>(_onecount);
    lock (_queue)
    {
    for (int i = _onecount - 1; i >= 0; i--)
    {
    if (_queue.Count > 0)
    {
    tempItems.Add(_queue.Dequeue());
    }
    }
    }
    tempItems.ForEach(_handler);

    }
    catch (Exception ex)
    {
    System.Diagnostics.Trace.TraceError(
    "ThreadProc error:{0}", ex);
    }

    Thread.Sleep(_inteval);
    }
    }

    private Queue<T> _queue = new Queue<T>();
    private Action<T> _handler = null;
    private int _inteval = 0;
    private int _onecount = 0;
    private Thread _t = null;
    }
  • 相关阅读:
    代码编译时JDK版本和运行时JDK版本不一致启动项目报错
    Apache 环境变量配置
    Android NDK 环境变量配置
    Android SDK 环境变量配置
    JAVA 环境变量配置
    FFmpeg Download
    JAVA SE Download
    VS 2015 Download
    BASS HOME
    C++11的闭包(lambda、function、bind)
  • 原文地址:https://www.cnblogs.com/onlytiancai/p/2099833.html
Copyright © 2020-2023  润新知