Advertisement
yakovmonarh

Singleton и многопоточность

Aug 20th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.05 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3. using System.Linq;
  4.  
  5. class Program
  6. {
  7.    static void Main(string[] args)
  8.    {
  9.         (new Thread(() =>
  10.     {
  11.         var comp2 = new Computer();
  12.         comp2.OS = OS.GetInstance("Windows 10");
  13.         Console.WriteLine(comp2.OS.Name);
  14.  
  15.     })).Start();
  16.  
  17.         (new Thread(() =>
  18.     {
  19.         var comp2 = new Computer();
  20.         comp2.OS = OS.GetInstance("Windows xp");
  21.         Console.WriteLine(comp2.OS.Name);
  22.  
  23.     })).Start();
  24.    
  25.     Console.ReadLine();
  26.    }
  27. }
  28.  
  29. class Computer
  30. {
  31.     public OS OS {get;set;}
  32.    
  33.     public void Launch(string osName)
  34.     {
  35.         this.OS = OS.GetInstance(osName);
  36.     }
  37. }
  38.  
  39. class OS
  40. {
  41.     private static OS instance;
  42.    
  43.     public static object syncRoot = new object();
  44.    
  45.     public string Name{get; private set;}
  46.    
  47.     protected OS(string name)
  48.     {
  49.         this.Name = name;
  50.     }
  51.    
  52.     public static OS GetInstance(string name)
  53.     {
  54.         if(instance == null)
  55.         {
  56.             lock(syncRoot)
  57.             {
  58.                 if(instance == null)
  59.                 {
  60.                     instance = new OS(name);
  61.                 }
  62.             }
  63.         }
  64.         return instance;
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement