Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.52 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Threading;
  7.  
  8. namespace ConsoleApplication1
  9. {
  10.     public class Program
  11.     {
  12.         static object obj = new object();
  13.         static string wiadomosc;
  14.         public static void Main()
  15.         {
  16.             Thread czytaj = new Thread(new ThreadStart(Czytajacy));
  17.             czytaj.Name = "Watek czytajacy";
  18.             Thread pisz = new Thread(new ThreadStart(Piszacy));
  19.             pisz.Name = "Watek piszacy";
  20.             pisz.Start();
  21.             czytaj.Start();
  22.             //pisz.Start();
  23.  
  24.             Console.ReadKey();
  25.         }
  26.  
  27.  
  28.         public static void Czytajacy()
  29.         {
  30.             Monitor.Enter(obj);
  31.             if (wiadomosc == null)
  32.             {
  33.                 Console.WriteLine("{0}: brak wiadomosci", Thread.CurrentThread.Name);
  34.                 Console.WriteLine("{0}: czekaj", Thread.CurrentThread.Name);
  35.                 Monitor.Wait(obj);
  36.             }
  37.             Console.WriteLine("{0}: {1}", Thread.CurrentThread.Name, wiadomosc);
  38.             Monitor.Exit(obj);
  39.  
  40.         }
  41.  
  42.         public static void Piszacy()
  43.         {
  44.             Monitor.Enter(obj);
  45.             wiadomosc = "Pozdrowienia!";
  46.             if (wiadomosc != null)
  47.             {
  48.                 Console.WriteLine("{0}: Wiadomość została wyslana", Thread.CurrentThread.Name);
  49.                 Monitor.Pulse(obj);
  50.             }
  51.             Monitor.Exit(obj);
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement