C#多线程,线程锁
 /*
  * User: Administrator
  * Email:798033502@qq.com
  * Date: 2013-7-18
  * Time: 22:54
  */
 using System;
 using System.Threading;
 
 namespace ThreadDome
 {
     class Program
     {
         //创建一个线程锁标识
         private static object threadLock = new object();
         public static void Main(string[] args)
         {
             //使10个线程全部指向同一个方法
             Thread [] threads = new Thread[10];
             for (int i = 0; i < 10; i++) {
                 threads[i]= new Thread(new ThreadStart(PrintNumbers));
                 threads[i].Name = string.Format("Worker thread{0}",i);
                 //设置为后台线程
                 threads[i].IsBackground =true;
             }
             //启动线程
             foreach (Thread t  in threads) {
                 t.Start();
             }
             
             Console.ReadKey();
         }
         
         public static  void PrintNumbers()
         {
             lock(threadLock)
             {
                 Console.WriteLine("线程——>{0}正在执行 ",Thread.CurrentThread.Name);
                 
                 for (int i = 0; i < 100; i++) {
                     Random r = new Random ();
                     Thread.Sleep(60*r.Next(6));
                     Console.WriteLine("{0}",i);
                 }
                 Console.WriteLine();
             }
         }
     }
 } 
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号