多线程简单应用示例

程序主题部分摘自msdn中Thread 类的示例说明,地址:http://msdn.microsoft.com/zh-cn/library/System.Threading.Thread(v=vs.110).aspx

附改动后的代码:

主体代码:

static void Main(string[] args)
        {
            Console.WriteLine("Main thread: Start a second thread.");

            List<Thread> listT = new List<Thread>();

            for (int i = 0; i < 5; i++)
            {
                Thread t = new Thread(new ThreadStart(ThreadProc));

                listT.Add(t);

                t.Start();
                //Thread.Sleep(0);
            }

            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine("Main thread: Do some work.");
                Thread.Sleep(0);
            }

            Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
            foreach (Thread t in listT)
            {
                t.Join();
            }
            Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.");
            Console.ReadLine();
        }

        public static void ThreadProc()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("ThreadProc: {0}", i);
                // Yield the rest of the time slice.
                Thread.Sleep(0);
            }
        }

 

需要单独控制线程停止,可给线程设置Name属性来实现。

posted @ 2013-12-31 15:18  被谋杀的诗篇  阅读(179)  评论(0编辑  收藏  举报