OKIEWARDOYO

VISUAL C# No.43 2

Jul 3rd, 2014
1,415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.42 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 readonly object lockObject = new object();
  12.        
  13.         public static void DisplayThread1()
  14.         {
  15.             while (stopThread != true)
  16.             {
  17.                 lock (lockObject)
  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.             }
  25.         }
  26.  
  27.         public static void DisplayThread2()
  28.         {
  29.             while (stopThread != true)
  30.             {
  31.                 lock (lockObject)
  32.                 {
  33.                     Console.WriteLine("\nDisplay Thread 2");
  34.                     outputText = "Saya Thread 2";
  35.                     Thread.Sleep(1000);
  36.                     Console.WriteLine("Thread 2 output --> {0}", outputText);
  37.                 }
  38.             }
  39.         }
  40.         static void Main(string[] args)
  41.         {
  42.             Thread thread1 = new Thread(DisplayThread1);
  43.             Thread thread2 = new Thread(DisplayThread2);
  44.  
  45.             // start them
  46.             thread1.Start();
  47.             thread2.Start();
  48.  
  49.             Console.ReadLine();
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment