using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace _2._1._1 { class TableOfElements { private Object thisLock = new Object(); int[] Arr; public int sum = 0; Random r = new Random(); public TableOfElements(int length) { Arr = new int[length]; for (int i = 0; i < length; i++) { Arr[i] = r.Next(-100, 1000); } } public void SumArr(int elementNumber) { lock(thisLock) { sum += Arr[elementNumber-1]; Console.WriteLine(this.sum); } } } class Program { static void Main(string[] args) { int n = 4; //number of elements in Array and threads TableOfElements tabOfEl = new TableOfElements(n); Thread[] threads = new Thread[n]; for (int j = 0; j < n; j++) { Thread thread = new Thread(() => tabOfEl.SumArr(j)); threads[j] = thread; } for (int i = 0; i < n; i++) { threads[i].Start(); } Thread.Sleep(1000); Console.WriteLine("Sum (multithreaded with lock): " + tabOfEl.sum); Console.ReadKey(); } } }