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

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 @ 2023-10-08 14:45  .Neterr  阅读(67)  评论(0编辑  收藏  举报