- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Threading;
- namespace BasicThreadSynchronization
- {
- class Program
- {
- static int count = 0;
- static object boton = new object();
- static void Main(string[] args)
- {
- Thread thread1 = new Thread(Increment);
- Thread thread2 = new Thread(Increment);
- thread1.Start();
- Thread.Sleep(500);
- thread2.Start();
- }
- static void Increment()
- {
- while (true)
- {
- lock(boton)
- {
- int temp = count;
- Thread.Sleep(1000);
- count = temp + 1;
- Console.WriteLine("theadID {1} - This is BasicThreadSynchronization: {0}", count, Thread.CurrentThread.ManagedThreadId);
- }
- Thread.Sleep(1000);
- }
- }
- }
- }
Output:
theadID 3 - This is BasicThreadSynchronization: 1
theadID 4 - This is BasicThreadSynchronization: 2
theadID 3 - This is BasicThreadSynchronization: 3
theadID 4 - This is BasicThreadSynchronization: 4
theadID 3 - This is BasicThreadSynchronization: 5
theadID 4 - This is BasicThreadSynchronization: 6
......