.NET多线程小记(3):线程的状态

线程的状态

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;



namespace MultiThreadTest

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Begin  Thread 1");

            Thread thread1 = new Thread(Task);



            Console.WriteLine("Start Thread 1");

            thread1.Start();

            PrintThreadState(thread1);



            Thread.Sleep(3 * 1000);

            Console.WriteLine("suspend thread1");



            thread1.Suspend();

            Thread.Sleep(1000);

            PrintThreadState(thread1);





            Console.WriteLine("Resume thread1");

            thread1.Resume();

            PrintThreadState(thread1);



            Console.WriteLine("Stop thread1");

            thread1.Abort();

            Thread.Sleep(1000);

            PrintThreadState(thread1);



            Console.WriteLine("Begin Thread 2");

            Thread thread2 = new Thread(Task2);

            thread2.Start();

            Thread.Sleep(2 * 1000);

            PrintThreadState(thread2);



            Thread.Sleep(10 * 1000);

            PrintThreadState(thread2);

            Console.Read();





        }



        private static void Task()

        {

            Console.WriteLine("Thread is running...");

            while (true) ;

        }



        private static void Task2()

        {

            Console.WriteLine("Thread start to sleep");



            Thread.Sleep(10 * 1000);

            Console.WriteLine("Thread was resumed");

        }



        private static void PrintThreadState(Thread thread)

        {

            Console.WriteLine("Thread's status is:{0}", 

                thread.ThreadState.ToString());

        }

    }

}

输出

image

你可能感兴趣的:(.net)