代码改变世界

.NET多线程小记(2):多线程示例

2009-11-06 14:53  敏捷的水  阅读(454)  评论(0编辑  收藏  举报

多线程示例:

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 Multi-Thread...");
            for (int i = 0; i < 5; i++)
            {
                Thread thread = new Thread(Task);

                thread.Start();
            }
            Console.Read();
        }

        private static void Task()
        {
            Console.WriteLine(
                string.Format("Thread {0} start",
                Thread.CurrentThread.ManagedThreadId.ToString()));

            Thread.Sleep(1000);

            Console.WriteLine(
                string.Format("Thread {0} End",
                Thread.CurrentThread.ManagedThreadId.ToString()));
        }
    }
}

输出:

clip_image002

注意:线程的生成是在调用Thread的Start方法的时候.