Code/C#

static field를 사용한 Thread

Hide Code 2007. 12. 9. 08:03
static field는 모든 Thread에서 공동으로 사용된다.

아래 예제를 살펴보자.

using System;
using System.Threading;

namespace ThreadTest
{
   class Program
   {
       // Static fields are shared between all threads
       static int count;

       static void Main(string[] args)
       {
           new Thread(Go).Start();
           Go();
       }

       static void Go()
       {
           for (int i = 0; i < 5; i++)
           {
               count++;
               Console.WriteLine(count);
           }
       }
   }
}


위의 예제에서 count는 static field이다.

두개의 thread가 count를 사용하는데, 공통으로 사용하게 된다.

실행 결과 화면은 아래와 같다.



2개의 thread가 공통의 instance를 사용한 앞의 예제와 동일한 결과를 얻었다.