Code/C#

[C#] Thread 샘플 코드 1

Hide Code 2007. 12. 7. 19:45
아래는 간단한 Thread 샘플 코드이다.

난수를 발생시키는 2개의 Thread가 있고, 발생한 난수만큼 Sleep 한다.



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

namespace SampleThread
{
   class Program
   {
       static void Main(string[] args)
       {
           myRandom = new Random();

           Thread t1 = new Thread(new ThreadStart(method1));
           t1.Start();

           Thread t2 = new Thread(new ThreadStart(method2));
           t2.Start();
       }

       private static void method1()
       {
           for (int i = 0; i < 5; i++)
           {
               r = myRandom.Next(6) * 1000;
               Console.WriteLine("[{0,-10}]", r);
               Thread.Sleep(r);
           }
       }

       private static void method2()
       {
           for (int i = 0; i < 5; i++)
           {
               r = myRandom.Next(6) * 1000;
               Console.WriteLine("[{0,10}]", r);
               Thread.Sleep(r);
           }
       }

       private static Random myRandom;
       private static int r;
   }
}