Advertisement
OKIEWARDOYO

VISUAL C# No.43 3

Jul 3rd, 2014
1,432
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.51 KB | None | 0 0
  1.  
  2. using System;
  3. using System.Threading;
  4.  
  5. namespace MultiThread
  6. {
  7.     class Program
  8.     {
  9.         private static string outputText = "";
  10.         private static Boolean stopThread = false;
  11.         private static Mutex MutexKu = new Mutex(); //buat mutex tanpa nama
  12.        
  13.         public static void DisplayThread1()
  14.         {
  15.             while (stopThread != true)
  16.             {
  17.                 MutexKu.WaitOne();//nunggu dulu untuk thread lain
  18.  
  19.                 Console.WriteLine("\nDisplay Thread 1");
  20.                 outputText = "Saya Thread 1";
  21.                 Thread.Sleep(1000);
  22.                 Console.WriteLine("Thread 1 output --> {0}", outputText);
  23.  
  24.                 MutexKu.ReleaseMutex(); //release mutex
  25.             }
  26.         }
  27.  
  28.         public static void DisplayThread2()
  29.         {
  30.             while (stopThread != true)
  31.             {
  32.                 MutexKu.WaitOne();//nunggu dulu untuk thread lain
  33.  
  34.                 Console.WriteLine("\nDisplay Thread 2");
  35.                 outputText = "Saya Thread 2";
  36.                 Thread.Sleep(1000);
  37.                 Console.WriteLine("Thread 2 output --> {0}", outputText);
  38.  
  39.                 MutexKu.ReleaseMutex(); //release mutex
  40.             }
  41.         }
  42.         static void Main(string[] args)
  43.         {
  44.             Thread thread1 = new Thread(DisplayThread1);
  45.             Thread thread2 = new Thread(DisplayThread2);
  46.  
  47.             // start them
  48.             thread1.Start();
  49.             thread2.Start();
  50.  
  51.             Console.ReadLine();
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement