程序中應該引起注意的地方:
SomeState類是一個保存信息的數據結構,它在程序中作為參數被傳遞給每一個線程,因為你需要把一些有用的信息封裝起來提供給線程,而這種方式是非常有效的。
程序出現的InterLocked類也是專為多線程程序而存在的,它提供了一些有用的原子操作。
原子操作:就是在多線程程序中,如果這個線程調用這個操作修改一個變量,那麼其他線程就不能修改這個變量了,這跟lock關鍵字在本質上是一樣的。
程序的輸出結果:
Thread Pool Sample:
Queuing 10 items to Thread Pool
Queue to Thread Pool 0
Queue to Thread Pool 1
Queue to Thread Pool 2
Queue to Thread Pool 3
Queue to Thread Pool 4
Queue to Thread Pool 5
2 0 :
HashCount.Count==0, Thread.CurrentThread.GetHashCode()==2
Queue to Thread Pool 6
Queue to Thread Pool 7
Queue to Thread Pool 8
Queue to Thread Pool 9
Waiting for Thread Pool to drain
4 1 :
HashCount.Count==1, Thread.CurrentThread.GetHashCode()==4
6 2 :
HashCount.Count==1, Thread.CurrentThread.GetHashCode()==6
7 3 :
HashCount.Count==1, Thread.CurrentThread.GetHashCode()==7
2 4 :
HashCount.Count==1, Thread.CurrentThread.GetHashCode()==2
8 5 :
HashCount.Count==2, Thread.CurrentThread.GetHashCode()==8
9 6 :
HashCount.Count==2, Thread.CurrentThread.GetHashCode()==9
10 7 :
HashCount.Count==2, Thread.CurrentThread.GetHashCode()==10
11 8 :
HashCount.Count==2, Thread.CurrentThread.GetHashCode()==11
4 9 :
HashCount.Count==2, Thread.CurrentThread.GetHashCode()==4
Setting eventX
Thread Pool has been drained (Event fired)
Load across threads
11 1
10 1
9 1
8 1
7 1
6 1
4 2
2 2
我們應該徹底地分析上面的程序,把握住線程池的本質,理解它存在的意義是什麼,這樣才能得心應手地使用它。