Thread execution with Thread.Sleep()works differently compare to normal execution. Lets take a example.
Suppose we have two thread thread1 and thread 2. in main program start thread1 first and then immidiatly start thread2 and inside both threads use sleep() to stop thread for few milliseconds. Sleep method use to block the current thread for a given time.
Lets run the same program without using sleep method.
Compare the output without sleep the execution of first thread complete first and then second thread starts and executes.
Thread Execution with Sleep() in C# Example:
using System;
using System.Text;
using System.Threading;
namespace Console_App
{
public class Class1
{
public void fun1()
{
for (int i = 0; i < 7; i++)
{
Console.Write(" #" + i );
Thread.Sleep(2);
}
}
public void fun2()
{
for (int i = 0; i < 7; i++)
{
Console.Write( " @" + i );
Thread.Sleep(2);
}
}
}
public class Class2
{
public static void Main()
{
Class1 a = new Class1();
Thread thread1 = new Thread(new ThreadStart(a.fun1));
Thread thread2 = new Thread(new ThreadStart(a.fun2));
thread1.Start();
thread2.Start();
Console.ReadLine();
}
}
}
0 comments:
Post a Comment