多线程例子

来源:互联网 发布:标志设计软件手机版 编辑:程序博客网 时间:2024/05/16 11:38

http://book.51cto.com/art/200806/77425.htm

class Test    {        static void Main()        {            PriorityTest work = new PriorityTest();            //创建线程并设置线程执行方法            Thread threadOne = new Thread(new ThreadStart(work.ThreadMethod));            threadOne.Name = "线程1";            Thread threadTwo = new Thread(new ThreadStart(work.ThreadMethod));            threadTwo.Name = "线程2";            //设置优先级            threadTwo.Priority = ThreadPriority.BelowNormal;            threadOne.Start(); threadTwo.Start();            //让两个线程都计算2秒钟            Thread.Sleep(2000);            //停止计算            work.LoopSwitch = false;        }    }    class PriorityTest    {        //用来控制While循环,为false就退出While循环        bool loopSwitch;        //构造方法        public PriorityTest()        {            loopSwitch = true;        }        public bool LoopSwitch        {            set { loopSwitch = value; }        }        //线程的方法,执行数数操作        public void ThreadMethod()        {            long threadCount = 0;            //进行加法操作            while (loopSwitch) { threadCount++; }            //显示结果            Console.WriteLine("{0},优先级:{1}" + "数到:{2}", Thread.CurrentThread.Name, Thread.CurrentThread.Priority.ToString(), threadCount.ToString());        }    }


 

原创粉丝点击