1 using System;
2 using System.Threading;
3 using System.Text;
4 using System.Threading.Tasks;
5
6 //多线程调试: 2013.10.08
7 //转自 http://www.cnblogs.com/yank/p/3227324.html
8 namespace ThreadExample
9 {
10 class SpinLockSample
11 {
12 public static void Test()
13 {
14 SpinLock sLock = new SpinLock();
15 StringBuilder sb = new StringBuilder();
16 Action action = () =>
17 {
18 bool gotLock = false;
19 for (int i = 0; i < 5; i++)
20 {
21 gotLock = false;
22 try
23 {
24 sLock.Enter(ref gotLock);
25 sb.Append(i.ToString());
26 }
27 catch (System.Exception ex)
28 {
29
30 }
31 finally
32 {
33 if (gotLock)
34 {
35 sLock.Exit();
36 }
37 }
38 }
39 };
40 //多线程调用action
41 Parallel.Invoke(action,action,action);
42 Console.WriteLine("Ouput {0}",sb.ToString());
43 }
44 }
45
46 class App
47 {
48 private static object UsingPrinterLocker = new object();
49 private static Mutex mutex = new Mutex();
50
51 public static void Main()
52 {
53 SpinLockSample.Test();
54 //TestPrint();
55 }
56
57 public static void TestPrint()
58 {
59 Thread thread;
60 Random random = new Random();
61
62 for (int i = 0; i < 10;i++ )
63 {
64 thread = new Thread(MyThreadProc);
65 thread.Name = string.Format("Thread {0}", i);
66 Thread.Sleep(random.Next(3));
67 thread.Start();
68 }
69 }
70
71 public static void MyThreadProc()
72 {
73 //UserPrinter();
74 //UsePrinterWithMutex();
75 UsePrinterWithMoniter();
76 }
77
78 public static void UsePrinterWithMutex()
79 {
80 mutex.WaitOne();
81 try
82 {
83 Console.WriteLine("{0} acquired thd lock", Thread.CurrentThread.Name);
84 Thread.Sleep(2000);
85 Console.WriteLine("{0} exiting lock.", Thread.CurrentThread.Name);
86 }
87 catch (System.Exception ex)
88 {
89
90 }
91 finally
92 {
93 mutex.ReleaseMutex();
94 }
95 }
96
97 public static void UsePrinterWithMoniter()
98 {
99 System.Threading.Monitor.Enter(UsingPrinterLocker);
100 try
101 {
102 Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name);
103 Thread.Sleep(500);
104 Console.WriteLine("{0} exit lock", Thread.CurrentThread.Name);
105 }
106 catch (System.Exception ex)
107 {
108
109 }
110 finally
111 {
112 System.Threading.Monitor.Exit(UsingPrinterLocker);
113 }
114 }
115
116 public static void UserPrinter()
117 {
118 lock (UsingPrinterLocker)
119 {
120 Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name);
121 Thread.Sleep(500);
122 Console.WriteLine("{0} exiting lock.", Thread.CurrentThread.Name);
123 }
124 }
125 }
126 }