为什么这段代码不会打印所有范围? (多线程问题)

时间:2019-05-07 20:03:11

标签: c# multithreading

我的多线程程序可以工作,但不能打印所有范围。我有100个号码;我将它们分为10个范围。我想在线程上做一些事情,例如打印范围,并根据这些范围继续我的想法。但是这些范围并不是所有预期范围。

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Test
{
    class Program
    {
        static int numberCount = 100;
        static int numberOfThreads = 10;
        static int numberOfFinishedThread = 0;
        static void Classifier(int lowIndex, int highIndex)
        {
            Console.WriteLine("L: " + lowIndex + "\tH: " + highIndex);
            numberOfFinishedThread++;
            if (numberOfFinishedThread == numberOfThreads)
            {
                Console.Write("Done. Press any key to exit.");
                Console.ReadLine();
            }
        }
        static void Main(string[] args)
        {
            int lowIndex, highIndex;
            for (int i = 0; i < numberOfThreads; i++)
            {
                lowIndex = (numberCount / numberOfThreads) * i;
                highIndex = (numberCount / numberOfThreads) * (i + 1);
                Thread thread = new Thread(() => Classifier(lowIndex, highIndex));
                thread.Start();
            }
        }
    }
}

pic

0 个答案:

没有答案