Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace ConsoleApplication1
- {
- class Program
- {
- static Queue<string> queue1 = new Queue<string>();
- static Queue<string> queue2 = new Queue<string>();
- public static Semaphore _pool;
- public static void AddFirst()
- {
- _pool.WaitOne();
- lock (queue1)
- {
- queue1.Enqueue(Thread.CurrentThread.Name);
- Console.WriteLine("В первую очередь был добавлен элемент: " + Thread.CurrentThread.Name);
- lock (queue2)
- {
- queue2.Enqueue(Thread.CurrentThread.Name);
- Console.WriteLine("Во вторую очередь был добавлен элемент: " + Thread.CurrentThread.Name);
- }
- }
- _pool.Release();
- }
- public static void AddSecond()
- {
- _pool.WaitOne();
- lock (queue2)
- {
- queue2.Enqueue(Thread.CurrentThread.Name);
- Console.WriteLine("Во вторую очередь был добавлен элемент: " + Thread.CurrentThread.Name);
- lock (queue1)
- {
- queue1.Enqueue(Thread.CurrentThread.Name);
- Console.WriteLine("В первую очередь был добавлен элемент: " + Thread.CurrentThread.Name);
- }
- }
- _pool.Release();
- }
- static void Main(string[] args)
- {
- _pool = new Semaphore(1, 1);
- Thread[] thread = new Thread[50];
- for (int i = 0; i < 50; i++)
- {
- if (i % 2 == 0)
- {
- thread[i] = new Thread(new ThreadStart(AddFirst));
- thread[i].Name = string.Format("#{0}", i + 1);
- }
- else
- {
- thread[i] = new Thread(new ThreadStart(AddSecond));
- thread[i].Name = string.Format("#{0}", i + 1);
- }
- }
- foreach (Thread t in thread)
- t.Start();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement