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

发布时间 2023-10-08 14:46:54作者: .Neterr
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;
            }
        }
    }
}