【多线程笔记】多线程处理队列数据

using System.Collections.Concurrent;
using System.Diagnostics;
{
    int threadCount = 20;
    List<Task> tasks = new List<Task>();
    ConcurrentQueue<int> queues = new ConcurrentQueue<int>();
    for (int i = 0; i < 1000; i++)
    {
        queues.Enqueue(i);
    }
    int index = 0;
    Stopwatch sw = Stopwatch.StartNew();
    sw.Start();
    for (int i = 0; i < threadCount; i++)
    {
        tasks.Add(Task.Run(() => Process()));
    }
    Task.WaitAll(tasks.ToArray());
    sw.Stop();
    Console.WriteLine($"线程数:{threadCount},耗时:{sw.ElapsedMilliseconds}");
    void Process()
    {
        while (true)
        {
            if (queues.TryDequeue(out int result))
            { 
                Thread.Sleep(20);
                int currentIndex = Interlocked.Increment(ref index);
                Console.WriteLine(  $"currentIndex:{currentIndex},result:{result}");
            }
            else
            {
                break;
            }
        }
    }
}
posted @   .Neterr  阅读(70)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示