C# 線程問題

1、帶參數的多線程調用

#region 執行帶一個參數的多線程

            Thread mythread = new Thread(new ParameterizedThreadStart(Calculate));

            mythread.IsBackground = true;      

            mythread.Start(500);

            #endregion

        private void Calculate(object Max)              //帶一個參數的委託函數 

        {

            int max = (int)Max;

            Stopwatch stopwatch = Stopwatch.StartNew();

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

            {

                Thread.Sleep(5);

            }

            stopwatch.Stop();

            long lSearchTime = stopwatch.ElapsedMilliseconds;

            MessageBox.Show(lSearchTime.ToString() + "毫秒");

        }
View Code

方式一: 定義一個類,將要傳的參數設置爲類的屬性,而後將參數值賦值給類的屬性,將類做爲一個參數進行傳達,如下代碼經過兩個參數示例,多個參數同樣,代碼以下:安全

class MyClass

    {

        public int Max { get; set; }

        public int Min { get; set; }

    }

            #region 第一種方式:執行帶多個參數的多線程

            MyClass model = new MyClass();

            model.Max = 500;

            model.Min = 0;

            Thread mythread1 = new Thread(new ParameterizedThreadStart(CalculateTwo));

            mythread1.IsBackground = true;      

            mythread1.Start(model);

            #endregion

        private void CalculateTwo(object Myclass)              //帶多個參數的委託函數 

        {

            MyClass model = (MyClass)Myclass;

            Stopwatch stopwatch = Stopwatch.StartNew();

            for (int i = model.Min; i < model.Max; i++)

            {

                Thread.Sleep(5);

            }

            stopwatch.Stop();

            long lSearchTime = stopwatch.ElapsedMilliseconds;

            MessageBox.Show(lSearchTime.ToString() + "毫秒");

        }
View Code

方式二:lambda表達式的方式,簡單方便,多線程

代碼以下:ide

#region 第二種方式:執行帶多個參數的多線程

            Thread mythread2 = new Thread(() => CalculateThree(500, 0));

            mythread2.IsBackground = true;        //設置為後臺線程,程式關閉後進程也關閉,若是不設置true,則程式關閉,此線程還在內存,不會關閉

            mythread2.Start();

            #endregion

        private void CalculateThree(int Max,int Min)              //帶多個參數的委託函數 

        {

            Stopwatch stopwatch = Stopwatch.StartNew();

            for (int i = Min; i < Max; i++)

            {

                Thread.Sleep(5);

            }

            stopwatch.Stop();

            long lSearchTime = stopwatch.ElapsedMilliseconds;

            MessageBox.Show(lSearchTime.ToString() + "毫秒");

        }
View Code

 

2、靜態變量和靜態方法的線程安全問題

  靜態方法內部建立的局部參數是線程安全的,不一樣線程調用同一個靜態方法時,他們不會共享靜態方法內部建立的參數,代碼舉例以下函數

public static void Test()
{
    int i = 0;
    Console.WriteLine(i);
    i++;
}

上面代碼中,變量i在不一樣線程間是不會共享的,不一樣線程分別調用該方法,輸出都是1,。this

靜態變量在不一樣線程間是共享的,這個相信你們都知道,而當靜態方法中對靜態變量進行操做時,這就涉及到了線程安全問題:spa

private static int i = 0;
public static void Test()
{
    Console.WriteLine(i);
    i++;
}

這段代碼在由不一樣線程進行操做時,存在線程安全問題,因此應該加鎖pwa

private static int i = 0;
public static void Test()
{
    lock(this)
    {   
        Console.WriteLine(i);
        i++;
    }
}
相關文章
相關標籤/搜索