1、如前所述,lock语句由编译器解析为Monitor类。Monitor类是一个静态类,有Enter和Exit方法。
1 using System; 2 using System.Text; 3 using System.Threading; 4 using System.Threading.Tasks; 5 6 class Program 7 { 8 static void Main(string[] args) 9 { 10 StringBuilder str = new StringBuilder(); 11 new Task(() => 12 { 13 for (int i = 0; i < 26; i++) 14 { 15 str.Append(((char)(‘A‘ + i)).ToString()); 16 } 17 str.Append("\n"); 18 }).Start(); 19 new Thread(() => 20 { 21 for (int i = 0; i < 26; i++) 22 { 23 str.Append(((char)(‘a‘ + i)).ToString()); 24 } 25 str.Append("\n"); 26 }).Start(); 27 Console.WriteLine(str); 28 Console.WriteLine("End the main thread."); 29 } 30 }
运行结果:
时间: 2024-11-05 13:41:04