336 Mutiple Threads

336 Mutiple Threads_第1张图片

336 Mutiple Threads_第2张图片

示例

Program.cs

namespace ThreadingApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Thread mainThread = Thread.CurrentThread;
            mainThread.Name = "Main thread";
            Console.WriteLine(mainThread.Name); //Main thread
            
            NumbersCounter numbersCounter = new NumbersCounter();

            ThreadStart ts1 = new ThreadStart(numbersCounter.CountUp);
            Thread t1 = new Thread(ts1);
            t1.Name = "CountUp Thread";
            Console.WriteLine($"{t1.Name} is {t1.ThreadState.ToString()}");
            t1.Start();
            Console.WriteLine($"{t1.Name} is {t1.ThreadState.ToString()}");

            ThreadStart ts2 = new ThreadStart(numbersCounter.CountDown);
            Thread t2 = new Thread(ts2);
            t2.Name = "CountDown Thread";
            Console.WriteLine($"{t2.Name} is {t2.ThreadState.ToString()}");
            t2.Start();
            Console.WriteLine($"{t2.Name} is {t2.ThreadState.ToString()}");


            Console.WriteLine(mainThread.Name + " completed");
            Console.ReadKey();
        }
    }

    class NumbersCounter
    {
        public void CountUp()
        {
            for (int i = 1; i <= 100000; i++)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write($"i = {i}, ");
            }
        }

        public void CountDown()
        {
            for (int j = 100000; j >=1; j--)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write($"j = {j}, ");
            }
        }
    }
}

你可能感兴趣的:(01,C#,12,.NET,8.0(完结),c#,.net)