C#线程使用(二)全面总结
一、C# Thread類的基本用法
通過(guò)System.Threading.Thread類可以開(kāi)始新的線程,并在線程堆棧中運(yùn)行靜態(tài)或?qū)嵗椒ā?梢酝ㄟ^(guò)Thread類的的構(gòu)造方法傳遞一個(gè)無(wú)參數(shù),并且不返回值(返回void)的委托(ThreadStart),這個(gè)委托的定義如下:[ComVisibleAttribute(true)]public delegate void ThreadStart()我們可以通過(guò)如下的方法來(lái)建立并運(yùn)行一個(gè)線程。復(fù)制代碼
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading;
6
7 namespace MyThread
8 {
9 class Program
10 {
11 public static void myStaticThreadMethod()
12 {
13 Console.WriteLine(“myStaticThreadMethod”);
14 }
15 static void Main(string[] args)
16 {
17 Thread thread1 = new Thread(myStaticThreadMethod);
18 thread1.Start(); // 只要使用Start方法,線程才會(huì)運(yùn)行
19 }
20 }
21 }
22
復(fù)制代碼
復(fù)制代碼
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading;
6
7 namespace MyThread
8 {
9 class Program
10 {
11 public void myThreadMethod()
12 {
13 Console.WriteLine(“myThreadMethod”);
14 }
15 static void Main(string[] args)
16 {
17 Thread thread2 = new Thread(new Program().myThreadMethod);
18 thread2.Start();
19 }
20 }
21 }
22
復(fù)制代碼
1 Thread thread3 = new Thread(delegate() { Console.WriteLine(“匿名委托”); });
2 thread3.Start();
3
4 Thread thread4 = new Thread(( ) => { Console.WriteLine(“Lambda表達(dá)式”); });
5 thread4.Start();
6
1 Thread thread5 = new Thread(()=>{ Console.WriteLine(Thread.CurrentThread.Name); });
2 thread5.Name = “我的Lamdba”;
3 thread5.Start();
一種可能的輸出結(jié)果
圖1
二、 定義一個(gè)線程類
我們可以將Thread類封裝在一個(gè)MyThread類中,以使任何從MyThread繼承的類都具有多線程能力。MyThread類的代碼如下:復(fù)制代碼
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading;
6 namespace MyThread
7 {
8 abstract class MyThread
9 {
10 Thread thread = null;
11
12 abstract public void run();
13
14 public void start()
15 {
16 if (thread == null)
17 thread = new Thread(run);
18 thread.Start();
19 }
20 }
21 }
22
復(fù)制代碼
復(fù)制代碼
1 class NewThread : MyThread
2 {
3 override public void run()
4 {
5 Console.WriteLine(“使用MyThread建立并運(yùn)行線程”);
6 }
7 }
8
9 static void Main(string[] args)
10 {
11
12 NewThread nt = new NewThread();
13 nt.start();
14 }
15
復(fù)制代碼
三、C# Thread類:為線程傳遞參數(shù)
Thread類有一個(gè)帶參數(shù)的委托類型的重載形式。這個(gè)委托的定義如下:[ComVisibleAttribute(false)]public delegate void ParameterizedThreadStart(Object obj)這個(gè)Thread類的構(gòu)造方法的定義如下:public Thread(ParameterizedThreadStart start);
下面的代碼使用了這個(gè)帶參數(shù)的委托向線程傳遞一個(gè)字符串參數(shù):
復(fù)制代碼
1 public static void myStaticParamThreadMethod(Object obj)
2 {
3 Console.WriteLine(obj);
4 }
5
6 static void Main(string[] args)
7 {
8 Thread thread = new Thread(myStaticParamThreadMethod);
9 thread.Start(“通過(guò)委托的參數(shù)傳值”);
10 }
11
復(fù)制代碼
復(fù)制代碼
1 class MyData
2 {
3 private String d1;
4 private int d2;
5 public MyData(String d1, int d2)
6 {
7 this.d1 = d1;
8 this.d2 = d2;
9 }
10 public void threadMethod()
11 {
12 Console.WriteLine(d1);
13 Console.WriteLine(d2);
14 }
15 }
16
17 MyData myData = new MyData(“abcd”,1234);
18 Thread thread = new Thread(myData.threadMethod);
19 thread.Start();
20
復(fù)制代碼
復(fù)制代碼
class NewThread : MyThread
{
private String p1;
private int p2;
public NewThread(String p1, int p2)
{
this.p1 = p1;
this.p2 = p2;
}
}
NewThread newThread = new NewThread(“hello world”, 4321);
newThread.start();
復(fù)制代碼
四、前臺(tái)和后臺(tái)線程
使用Thread建立的線程默認(rèn)情況下是前臺(tái)線程,在進(jìn)程中,只要有一個(gè)前臺(tái)線程未退出,進(jìn)程就不會(huì)終止。主線程就是一個(gè)前臺(tái)線程。而后臺(tái)線程不管線程是否結(jié)束,只要所有的前臺(tái)線程都退出(包括正常退出和異常退出)后,進(jìn)程就會(huì)自動(dòng)終止。一般后臺(tái)線程用于處理時(shí)間較短的任務(wù),如在一個(gè)Web服務(wù)器中可以利用后臺(tái)線程來(lái)處理客戶端發(fā)過(guò)來(lái)的請(qǐng)求信息。而前臺(tái)線程一般用于處理需要長(zhǎng)時(shí)間等待的任務(wù),如在Web服務(wù)器中的監(jiān)聽(tīng)客戶端請(qǐng)求的程序,或是定時(shí)對(duì)某些系統(tǒng)資源進(jìn)行掃描的程序。下面的代碼演示了前臺(tái)和后臺(tái)線程的區(qū)別。復(fù)制代碼
1 public static void myStaticThreadMethod()
2 {
3 Thread.Sleep(3000);
4 }
5
6 Thread thread = new Thread(myStaticThreadMethod);
7 // thread.IsBackground = true;
8 thread.Start();
復(fù)制代碼
五、C# Thread類:判斷多個(gè)線程是否都結(jié)束的兩種方法
確定所有線程是否都完成了工作的方法有很多,如可以采用類似于對(duì)象計(jì)數(shù)器的方法,所謂對(duì)象計(jì)數(shù)器,就是一個(gè)對(duì)象被引用一次,這個(gè)計(jì)數(shù)器就加1,銷毀引用就減1,如果引用數(shù)為0,則垃圾搜集器就會(huì)對(duì)這些引用數(shù)為0的對(duì)象進(jìn)行回收。方法一:線程計(jì)數(shù)器線程也可以采用計(jì)數(shù)器的方法,即為所有需要監(jiān)視的線程設(shè)一個(gè)線程計(jì)數(shù)器,每開(kāi)始一個(gè)線程,在線程的執(zhí)行方法中為這個(gè)計(jì)數(shù)器加1,如果某個(gè)線程結(jié)束(在線程執(zhí)行方法的最后為這個(gè)計(jì)數(shù)器減1),為這個(gè)計(jì)數(shù)器減1。然后再開(kāi)始一個(gè)線程,按著一定的時(shí)間間隔來(lái)監(jiān)視這個(gè)計(jì)數(shù)器,如是棕個(gè)計(jì)數(shù)器為0,說(shuō)明所有的線程都結(jié)束了。當(dāng)然,也可以不用這個(gè)監(jiān)視線程,而在每一個(gè)工作線程的最后(在為計(jì)數(shù)器減1的代碼的后面)來(lái)監(jiān)視這個(gè)計(jì)數(shù)器,也就是說(shuō),每一個(gè)工作線程在退出之前,還要負(fù)責(zé)檢測(cè)這個(gè)計(jì)數(shù)器。使用這種方法不要忘了同步這個(gè)計(jì)數(shù)器變量啊,否則會(huì)產(chǎn)生意想不到的后果。方法二:使用Thread.join方法join方法只有在線程結(jié)束時(shí)才繼續(xù)執(zhí)行下面的語(yǔ)句。可以對(duì)每一個(gè)線程調(diào)用它的join方法,但要注意,這個(gè)調(diào)用要在另一個(gè)線程里,而不要在主線程,否則程序會(huì)被阻塞的。個(gè)人感覺(jué)這種方法比較好。線程計(jì)數(shù)器方法演示:復(fù)制代碼
1 class ThreadCounter : MyThread
2 {
3 private static int count = 0;
4 private int ms;
5 private static void increment()
6 {
7 lock (typeof(ThreadCounter)) // 必須同步計(jì)數(shù)器
8 {
9 count++;
10 }
11 }
12 private static void decrease()
13 {
14 lock (typeof(ThreadCounter))
15 {
16 count–;
17 }
18 }
19 private static int getCount()
20 {
21 lock (typeof(ThreadCounter))
22 {
23 return count;
24 }
25 }
26 public ThreadCounter(int ms)
27 {
28 this.ms = ms;
29 }
30 override public void run()
31 {
32 increment();
33 Thread.Sleep(ms);
34 Console.WriteLine(ms.ToString()+“毫秒任務(wù)結(jié)束”);
35 decrease();
36 if (getCount() == 0)
37 Console.WriteLine(“所有任務(wù)結(jié)束”);
38 }
39 }
40
41
42 ThreadCounter counter1 = new ThreadCounter(3000);
43 ThreadCounter counter2 = new ThreadCounter(5000);
44 ThreadCounter counter3 = new ThreadCounter(7000);
45
46 counter1.start();
47 counter2.start();
48 counter3.start();
49
復(fù)制代碼
1 public ThreadCounter(int ms)
2 {
3 this.ms = ms;
4 increment();
5 }
圖2
圖2
使用Thread.join方法演示復(fù)制代碼
1 private static void threadMethod(Object obj)
2 {
3 Thread.Sleep(Int32.Parse(obj.ToString()));
4 Console.WriteLine(obj + “毫秒任務(wù)結(jié)束”);
5 }
6 private static void joinAllThread(object obj)
7 {
8 Thread[] threads = obj as Thread[];
9 foreach (Thread t in threads)
10 t.Join();
11 Console.WriteLine(“所有的線程結(jié)束”);
12 }
13
14 static void Main(string[] args)
15 {
16 Thread thread1 = new Thread(threadMethod);
17 Thread thread2 = new Thread(threadMethod);
18 Thread thread3 = new Thread(threadMethod);
19
20 thread1.Start(3000);
21 thread2.Start(5000);
22 thread3.Start(7000);
23
24 Thread joinThread = new Thread(joinAllThread);
25 joinThread.Start(new Thread[] { thread1, thread2, thread3 });
26
27 }
28
復(fù)制代碼
總結(jié)
以上是生活随笔為你收集整理的C#线程使用(二)全面总结的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C#线程的使用和测试
- 下一篇: C# XML操作