프로그래밍/C# Thread 예제 곰환 2017. 4. 3. 09:34 using System; using System.Threading; namespace Thread_Console { class MyThreadClass { //string 인사를 입력값으로 받고, //이 값을 자신의 스레드에서 무작위의 주기로 //콘솔에 10번 출력한다. private const int RANDOM_SLEEP_MAX = 500; // 무작위로 대기할 경우의 최대 시간 private const int LOOP_COUNT = 10; // 메세지를 출력할 횟수 private String greeting; public MyThreadClass(String greeting) { this.greeting = greeting; } public void runMyThread() { Random rand = new Random(); for (int x = 0; x < LOOP_COUNT; x++) { Console.WriteLine("Thread-" + Thread.CurrentThread.GetHashCode() + ": " + greeting + " {0}번째 작업", x); try { Thread.Sleep(rand.Next(RANDOM_SLEEP_MAX)); // 0에서 RANDOM_SLEEP_MAX 만큼 대기한다. } catch (ThreadInterruptedException) { } // 실행되지 않는다. } } } class Program { static void Main(string[] args) { MyThreadClass mtc1 = new MyThreadClass("Hello"); new Thread(new ThreadStart(mtc1.runMyThread)).Start(); MyThreadClass mtc2 = new MyThreadClass("Hello"); new Thread(new ThreadStart(mtc2.runMyThread)).Start(); MyThreadClass mtc3 = new MyThreadClass("Hello"); new Thread(new ThreadStart(mtc3.runMyThread)).Start(); } } }