Shared Resource : synchronized « Thread « C# / CSharp Tutorial






using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

   class Tester{
      static int counter = 0;
      static void Main()
      {
         Thread t1 = new Thread( new ThreadStart( Incrementer ) );
         t1.IsBackground = true;
         t1.Name = "ThreadOne";
         t1.Start();
         Console.WriteLine( "Started thread {0}",t1.Name );

         Thread t2 = new Thread( new ThreadStart( Incrementer ) );
         t2.IsBackground = true;
         t2.Name = "ThreadTwo";
         t2.Start();
         Console.WriteLine( "Started thread {0}",t2.Name );
         t1.Join();
         t2.Join();
      }
      public static void Incrementer(){
         try{
            while ( counter < 1000 )
            {
               int temp = counter;
               temp++; 
               Thread.Sleep( 1 );
               counter = temp;
               Console.WriteLine("Thread {0}. Incrementer: {1}",Thread.CurrentThread.Name,counter );
            }
         }catch ( ThreadInterruptedException ){
            Console.WriteLine("Thread {0} interrupted! Cleaning up...",Thread.CurrentThread.Name );
         }
         finally
         {
            Console.WriteLine("Thread {0} Exiting. ",Thread.CurrentThread.Name );
         }
      }
   }








20.16.synchronized
20.16.1.Using synchronized methods
20.16.2.Sync Delegate
20.16.3.Shared Resource
20.16.4.Synchronous Writing, Asynchronous Reading