C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace SynchronisingThreads
{
public class ABC
{
private object thislock = new object();
public void A()
{
Console.WriteLine("Starting" + Thread.CurrentThread.Name.ToString());
int x = 10;
int y = 30;
int sum = 0;
lock (thislock)
{
sum = x + y;
Console.WriteLine(sum);
}
Thread.Sleep(5000);
Console.WriteLine(Thread.CurrentThread.Name.ToString() +"is stopped" );
}
public static void Main(string[] args)
{
ABC a1 = new ABC();
Thread t1 = new Thread(new ThreadStart(a1.A));
Thread t2 = new Thread(new ThreadStart(a1.A));
t1.Name = " T1 ";
t2.Name = " T2 ";
t1.Start();
t2.Start();
Console.ReadKey();
}
}
}
Output:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace SynchronisingThreads
{
public class ABC
{
private object thislock = new object();
public void A()
{
Console.WriteLine("Starting" + Thread.CurrentThread.Name.ToString());
int x = 10;
int y = 30;
int sum = 0;
lock (thislock)
{
sum = x + y;
Console.WriteLine(sum);
}
Thread.Sleep(5000);
Console.WriteLine(Thread.CurrentThread.Name.ToString() +"is stopped" );
}
public static void Main(string[] args)
{
ABC a1 = new ABC();
Thread t1 = new Thread(new ThreadStart(a1.A));
Thread t2 = new Thread(new ThreadStart(a1.A));
t1.Name = " T1 ";
t2.Name = " T2 ";
t1.Start();
t2.Start();
Console.ReadKey();
}
}
}
Output:
No comments:
Post a Comment