C#线程示例二

来源:互联网 发布:网络系统验收标准 编辑:程序博客网 时间:2024/06/01 10:52

这是一个线简单明了的线程小程序,用于输出给定数内的奇、偶数。

using System;

using System.Collections.Generic;

using System.Text;

using System.Threading;

namespace JiOuShu

{

    class Program

    {

        static void Main(string[] args)

        {

            //ThreadStart thrSta = new ThreadStart();

            //实例化一个有参委托

            ParameterizedThreadStart ParTerThrSta1 = new ParameterizedThreadStart(ShuChuJishu);

            Thread thr1 = new Thread(ParTerThrSta1);       //实例化一个线程

            thr1.Name = "线程A:";      //给线程起个名字

            thr1.Priority = ThreadPriority.Highest;   //设置A线程的级别为最高

          

            ParameterizedThreadStart parTerThrSta2 = new ParameterizedThreadStart(ShuChuOushu);

            Thread thr2 = new Thread(parTerThrSta2);

            thr2.Name = "线程B:";

            thr2.Priority = ThreadPriority.Lowest;     //设置B线程的级别为最低

            thr1.Start(50);       //开启线程并传入一个参数

            thr2.Start(50);

        }

        public static void ShuChuJishu(object num)

        {

            for (int i = 0; i <= (int)num; i++)

            {

                if (i % 2 != 0)

                {

                    Console.Write("{0}输出奇数:{1}",Thread.CurrentThread.Name,i);

                    Console.WriteLine();

                    Console.WriteLine();

                    Thread.Sleep(1000);  //设备间隔时间

                }

            }

        }

        public static void ShuChuOushu(object num)

        {

            for (int i = 0; i <= (int)num; i++)

            {

                if (i % 2 == 0)

                {

                    Console.Write("{0}输出偶数:{1}",Thread.CurrentThread.Name,i);

                    Console.WriteLine();

                    Console.WriteLine();

                    Thread.Sleep(1000);  //设备间隔时间

                }

            }

        }

    }

}

原创粉丝点击