Advertisement
Guest User

Threads

a guest
Nov 21st, 2014
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 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 Threading
  9. {
  10.     class Program
  11.     {
  12.           private static Mutex mutex = new Mutex();
  13.           private static int Sum = 0;
  14.  
  15.             static void Main(string[] args)
  16.             {
  17.  
  18.                 Thread[] _workers = new Thread[1000];
  19.  
  20.                 for (int i = 0; i < _workers.Length; i++)
  21.                 {
  22.                     _workers[i] = new Thread(new ParameterizedThreadStart(MutexDemo));
  23.                     _workers[i].Name = string.Format("Thread {0} :", i + 1);
  24.                     _workers[i].Start(i);
  25.                 }
  26.  
  27.                 foreach (Thread thread in _workers)
  28.                 {
  29.                     thread.Join();
  30.  
  31.                 }
  32.                 Console.WriteLine(Sum);
  33.                 Console.ReadKey();
  34.             }
  35.  
  36.             static void MutexDemo(object custom)
  37.             {
  38.                 try
  39.                 {
  40.                    mutex.WaitOne();
  41.  
  42.                     int i = (int)custom;
  43.  
  44.                     Console.WriteLine("{0} вошел в метод",
  45.                         Thread.CurrentThread.Name);
  46.                     Console.WriteLine("Сумма до - {0}, i = {1}",Sum,i);
  47.                     if (i%2 == 0)
  48.                     {
  49.                         Sum = Sum + i * 10;
  50.                     }
  51.                     else
  52.                     {
  53.                         Sum = Sum - i * 10;
  54.                     }                              
  55.                    
  56.                     Thread.Sleep((new Random().Next(1,100)));
  57.                     Console.WriteLine("Сумма после - {0}, i = {1}", Sum, i);
  58.                     Console.WriteLine("{0} вышел из метода",
  59.                         Thread.CurrentThread.Name);
  60.  
  61.                 }
  62.                 finally
  63.                 {
  64.                     mutex.ReleaseMutex();
  65.                 }
  66.             }
  67.         }
  68.    
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement