[go: up one dir, main page]

0% found this document useful (0 votes)
31 views2 pages

Multi Threading Demo

The document contains two C# programs demonstrating multithreading using the Thread class. The first program creates two threads that execute different methods, Show and Display, while the second program modifies the Show method to use a locking mechanism with Monitor to ensure thread safety. Both programs print characters and numbers along with the thread names to the console, illustrating concurrent execution.

Uploaded by

DJ Trap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views2 pages

Multi Threading Demo

The document contains two C# programs demonstrating multithreading using the Thread class. The first program creates two threads that execute different methods, Show and Display, while the second program modifies the Show method to use a locking mechanism with Monitor to ensure thread safety. Both programs print characters and numbers along with the thread names to the console, illustrating concurrent execution.

Uploaded by

DJ Trap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

using System;

using System.Threading;
namespace MultithreadingDemo01Kcmt
{
class Abc
{
public void Show()
{
for (char alph = 'a'; alph != 'z'; alph++)
{
Console.WriteLine(alph+"\t"+Thread.CurrentThread.Name);
Thread.Sleep(200);
}
}
public void Display()
{
for (int i = 0; i <= 26; i++)
{
Console.WriteLine(i + "\t" + Thread.CurrentThread.Name);
Thread.Sleep(200);
}
}
}
class Program
{
static void Main()
{
Abc obj1 = new Abc();
//1.0
//obj1.Show();
//obj1.Display();
//1.1
Thread t1 = new Thread(obj1.Show);
t1.Name = "First User defined thread";
Thread t2 = new Thread(obj1.Display);
t2.Name = "Second user defined thread";
t1.Start();
t2.Start();
Console.ReadKey();
}
}
}
+++++++++++++++++++++++++++++++++++++++++++++
using System;
using System.Threading;
namespace MultithreadingDemo01Kcmt
{
class Abc
{
public void Show()
{
//lock (this)
//{
// for (char alph = 'a'; alph != 'z'; alph++)
// {
// Console.WriteLine(alph + "\t" + Thread.CurrentThread.Name);
// Thread.Sleep(200);
// }
//}
//or
Monitor.Enter(this);
for (char alph = 'a'; alph != 'z'; alph++)
{
Console.WriteLine(alph + "\t" + Thread.CurrentThread.Name);
Thread.Sleep(200);
}
Monitor.Exit(this);

}
class Program
{
static void Main()
{
Abc obj1 = new Abc();
Thread t1 = new Thread(obj1.Show);
t1.Name = "First User defined thread";
Thread t2 = new Thread(obj1.Show);
t2.Name = "Second user defined thread";
t1.Start();
t2.Start();
Console.ReadKey();
}
}
}

You might also like