在有资源争夺时,可以用Lock进行锁定对象:
1
/*
2 Example14_8.cs illustrates the use of the lock object
3 */
4
5 using System;
6 using System.Threading;
7
8 class Example14_8
9 {
10 // a shared counter
11 private int Runs = 0 ;
12
13 // the CountUp method increments the shared counter
14 public void CountUp()
15 {
16 while (Runs < 10 )
17 {
18 lock ( this )
19 {
20 int Temp = Runs;
21 Temp ++ ;
22 Console.WriteLine(Thread.CurrentThread.Name + " " + Temp);
23 Thread.Sleep( 1000 );
24 Runs = Temp;
25 }
26 }
27 }
28
29 public static void Main()
30 {
31 // Make an instance of this class
32 Example14_8 ex = new Example14_8();
33
34 // And run the test outside of the static method
35 ex.RunThreads();
36 }
37
38 public void RunThreads()
39 {
40 // create and launch two threads
41 Thread t2 = new Thread( new ThreadStart(CountUp));
42 t2.Name = " t2 " ;
43 Thread t3 = new Thread( new ThreadStart(CountUp));
44 t3.Name = " t3 " ;
45 t2.Start();
46 t3.Start();
47
48 }
49
50 }
2 Example14_8.cs illustrates the use of the lock object
3 */
4
5 using System;
6 using System.Threading;
7
8 class Example14_8
9 {
10 // a shared counter
11 private int Runs = 0 ;
12
13 // the CountUp method increments the shared counter
14 public void CountUp()
15 {
16 while (Runs < 10 )
17 {
18 lock ( this )
19 {
20 int Temp = Runs;
21 Temp ++ ;
22 Console.WriteLine(Thread.CurrentThread.Name + " " + Temp);
23 Thread.Sleep( 1000 );
24 Runs = Temp;
25 }
26 }
27 }
28
29 public static void Main()
30 {
31 // Make an instance of this class
32 Example14_8 ex = new Example14_8();
33
34 // And run the test outside of the static method
35 ex.RunThreads();
36 }
37
38 public void RunThreads()
39 {
40 // create and launch two threads
41 Thread t2 = new Thread( new ThreadStart(CountUp));
42 t2.Name = " t2 " ;
43 Thread t3 = new Thread( new ThreadStart(CountUp));
44 t3.Name = " t3 " ;
45 t2.Start();
46 t3.Start();
47
48 }
49
50 }