上一篇中讲述了简单的C#多线程程序编写,应该说并不具备太多的难点,这个程序中,我们将编写一个比较特殊的线程,两个线程需要操作同一个List<int>对象:

 

 1  class ThreadCollection{
 2         List<int> elements = new List<int>();
 3         public ThreadCollection(){
 4             elements.Add(10);
 5             elements.Add(20);
 6         }
 7     
 8         public void Run()
 9         {
10             Thread.Sleep(1000);
11             foreachint item in elements){
12                 Console.WriteLine("Item (" + item + " ) ");
13                 Thread.Sleep(1000);
14             }
15 
16         }
17 
18         public void Add()
19         {
20             Thread.Sleep(1500);
21             elements.Add(30);
22         }
23 
24     }
25 
26 
27     ThreadCollection coll = new ThreadCollection();
28     Thread thread3 = new Thread(
29                new ThreadStart(coll.Run)
30             );
31     Thread thread4 = new Thread(
32                new ThreadStart(coll.Add)
33     );
34 
35     thread3.Start();
36     thread4.Start();
37 

相关文章: