執行緒的啟動

iamzxf發表於2015-05-15

    執行緒的啟動有兩種辦法,第一種方法是使用帶委託函式的Thread類建構函式,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace threadDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread thread1 = new Thread(new ThreadStart(runner));
            thread1.Start();
            Console.WriteLine("執行main函式");

            Console.ReadLine();
        }
        static void runner()
        {
            Console.WriteLine("執行runner函式");
        }
    }
}


    第二種是自定義一個類,把執行緒的方法定義為例項方法,初始化例項的資料,然後啟動執行緒。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace threadDemo
{
    class myClass
    {
        private string msg;
        public myClass(string msg)
        {
            this.msg = msg;
        }

        public void ThreadMain()
        {
            Console.WriteLine("msg的值是{0}",this.msg);
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            myClass mtc = new myClass("success");
            Thread thread1 = new Thread(mtc.ThreadMain);
            thread1.Start();
            Console.ReadLine();
        }
    }
}


相關文章