C#線程實例

在執行線程時可以調用靜態和非靜態方法。要調用靜態和非靜態方法,需要在ThreadStart類的構造函數中傳遞方法名稱。對於靜態方法,不需要創建類的實例。可以通過類的名稱來引用它。

using System;
using System.Threading;
public class MyThread
{
    public static void Thread1()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("Thread1: "+i);
        }
    }
}
public class ThreadExample
{
    public static void Main()
    {
        Thread t1 = new Thread(new ThreadStart(MyThread.Thread1));
        Thread t2 = new Thread(new ThreadStart(MyThread.Thread1));
        t1.Start();
        t2.Start();
    }
}

上述程序的輸出可以是任何東西,因爲線程之間有上下文切換。在我運行上面示例時輸出以下結果 -

Thread1: 0
Thread1: 1
Thread1: 0
Thread1: 1
Thread1: 2
Thread1: 3
Thread1: 4
Thread1: 5
Thread1: 6
Thread1: 7
Thread1: 8
Thread1: 2
Thread1: 3
Thread1: 4
Thread1: 5
Thread1: 6
Thread1: 7
Thread1: 8
Thread1: 9
Thread1: 9

C# 線程示例:非靜態方法

對於非靜態方法,需要創建類的實例,以便我們可以在ThreadStart類的構造函數中引用它。

using System;
using System.Threading;

public class MyThread
{
    private String name;

    public MyThread(String name)
    {
        this.name = name;
    }
    public void Thread1()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine(this.name+": "+i);
        }
    }
}

public class ThreadExample
{
    public static void Main()
    {
        MyThread mt = new MyThread("Thread1");
        MyThread mt2 = new MyThread("Thread2");
        Thread t1 = new Thread(new ThreadStart(mt.Thread1));
        Thread t2 = new Thread(new ThreadStart(mt2.Thread1));
        t1.Start();
        t2.Start();
    }
}

這個程序的輸出可以是任何順序,因爲線程之間有上下文切換,所以每次執行的結果都不太一樣。輸出結果如下所示 -

Thread1: 0
Thread1: 1
Thread2: 0
Thread2: 1
Thread2: 2
Thread2: 3
Thread2: 4
Thread2: 5
Thread2: 6
Thread2: 7
Thread2: 8
Thread2: 9
Thread1: 2
Thread1: 3
Thread1: 4
Thread1: 5
Thread1: 6
Thread1: 7
Thread1: 8
Thread1: 9

C# 線程示例:在每個線程上執行不同的任務

下面讓我們來看看另外一個例子,在每個線程上執行不同的方法。

using System;
using System.Threading;

public class MyThread
{
    public static void method1()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("This is method1 :" + i);
        }
    }
    public static void method2()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("This is method2 :"+i);
        }

    }
}
public class ThreadExample
{
    public static void Main()
    {
        Thread t1 = new Thread(new ThreadStart(MyThread.method1));
        Thread t2 = new Thread(new ThreadStart(MyThread.method2));
        t1.Start();
        t2.Start();
    }
}

這個程序的輸出可以是任何順序,因爲線程之間有上下文切換,所以每次執行的結果都不太一樣。輸出結果如下所示 -

This is method1 :0
This is method1 :1
This is method2 :0
This is method2 :1
This is method2 :2
This is method2 :3
This is method2 :4
This is method1 :2
This is method1 :3
This is method1 :4