Advertisement
Guest User

Untitled

a guest
Feb 11th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.36 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7.  
  8. namespace ConsoleApplication1
  9. {
  10.     class Program
  11.     {
  12.         static Queue<string> queue1 = new Queue<string>();
  13.         static Queue<string> queue2 = new Queue<string>();
  14.         public static Semaphore _pool;
  15.  
  16.    
  17.         public static void AddFirst()
  18.         {
  19.             _pool.WaitOne();
  20.             lock (queue1)
  21.             {
  22.                 queue1.Enqueue(Thread.CurrentThread.Name);
  23.                 Console.WriteLine("В первую очередь был добавлен элемент: " + Thread.CurrentThread.Name);
  24.                 lock (queue2)
  25.                 {
  26.                     queue2.Enqueue(Thread.CurrentThread.Name);
  27.                     Console.WriteLine("Во вторую очередь был добавлен элемент: " + Thread.CurrentThread.Name);
  28.                 }
  29.             }
  30.             _pool.Release();
  31.         }
  32.  
  33.         public static void AddSecond()
  34.         {
  35.             _pool.WaitOne();
  36.             lock (queue2)
  37.             {
  38.                 queue2.Enqueue(Thread.CurrentThread.Name);
  39.                 Console.WriteLine("Во вторую очередь был добавлен элемент: " + Thread.CurrentThread.Name);
  40.                 lock (queue1)
  41.                 {
  42.                     queue1.Enqueue(Thread.CurrentThread.Name);
  43.                     Console.WriteLine("В первую очередь был добавлен элемент: " + Thread.CurrentThread.Name);
  44.                 }
  45.             }
  46.             _pool.Release();
  47.         }
  48.    
  49.  
  50.           static void Main(string[] args)
  51.         {
  52.             _pool = new Semaphore(1, 1);
  53.             Thread[] thread = new Thread[50];
  54.             for (int i = 0; i < 50; i++)
  55.             {
  56.                 if (i % 2 == 0)
  57.                 {
  58.                     thread[i] = new Thread(new ThreadStart(AddFirst));
  59.                     thread[i].Name = string.Format("#{0}", i + 1);
  60.                 }
  61.                 else
  62.                 {
  63.                     thread[i] = new Thread(new ThreadStart(AddSecond));
  64.                     thread[i].Name = string.Format("#{0}", i + 1);
  65.                 }
  66.  
  67.             }
  68.             foreach (Thread t in thread)
  69.                 t.Start();
  70.  
  71.         }
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement