在執(zhí)行線程時(shí)可以調(diào)用靜態(tài)和非靜態(tài)方法。要調(diào)用靜態(tài)和非靜態(tài)方法,需要在ThreadStart類的構(gòu)造函數(shù)中傳遞方法名稱。對(duì)于靜態(tài)方法,不需要?jiǎng)?chuàng)建類的實(shí)例??梢酝ㄟ^類的名稱來引用它。
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();
}
}
上述程序的輸出可以是任何東西,因?yàn)榫€程之間有上下文切換。在我運(yùn)行上面示例時(shí)輸出以下結(jié)果 -
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
對(duì)于非靜態(tài)方法,需要?jiǎng)?chuàng)建類的實(shí)例,以便我們可以在ThreadStart類的構(gòu)造函數(shù)中引用它。
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();
}
}
這個(gè)程序的輸出可以是任何順序,因?yàn)榫€程之間有上下文切換,所以每次執(zhí)行的結(jié)果都不太一樣。輸出結(jié)果如下所示 -
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
下面讓我們來看看另外一個(gè)例子,在每個(gè)線程上執(zhí)行不同的方法。
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();
}
}
這個(gè)程序的輸出可以是任何順序,因?yàn)榫€程之間有上下文切換,所以每次執(zhí)行的結(jié)果都不太一樣。輸出結(jié)果如下所示 -
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