Sunday, March 9, 2014

Multi Threading & Thread State


Multi Threading

  • Multi Threading is one of the rich features of .NET applications.
  • Using this feature, the user is able to create multi-threaded applications.
  • This concept is introduced in VC++. This is also supported by Java.
  • Definition of Multi Threading: The ability of an application that maintains multiple threads at run time.
  • Definition of Thread: The thread is a sub process (part of the process). That means it has some code to execute.
  • Advantage of Multi-Threading: Using multi threading‖, you can break a complex task in a single application into multiple threads that execute independently and simultaneously.
  • In other words, multi threading is the sub form of multi tasking.
  • Before starting with the implementation of Multi Threading, you should recollect the concept of Multi-Tasking.
MULTI TASKING:
  • Def: Ability of the OS, that is able to perform more than one task, at-a-time (simultaneously) is called as Multi-Tasking.
  • As a part of this, OS allocates the CPU clock (CPU capacity) for each task.

Note: Just like multi-tasking, OS allocates the CPU clock for each thread.

THREADING ARCHITECTURE

Implementation of Multi Threading:

.NET Framework offers a namespace called “System.Threading” for implementation of multi threading.

Library: System.Threading.Thread
This class object represents a thread.
  • Import the API:
  • using System.Threading;
  • Create the Thread Object:
  • Thread th = new Thread(method name);
  • Start the Thread:
  • th.Start()
Program for Multi-Threading
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace SimpleThreadingDemo
{
class ThreadingDemo
 {
  private void FirstMethod()
  {
   for (int i = 1; i <= 300; i++)
   Console.Write("i=" + i + " ");
  }
  private void SecondMethod()
  {
   for (int j = 1; j <= 300; j++)
   Console.Write("j=" + j + " ");
  }
  public void Display()
   {
    Thread th1 = new Thread(FirstMethod);
    Thread th2 = new Thread(SecondMethod);
    th1.Start();
    th2.Start(); 
   }
 }
 class Program
  {
   static void Main(string[] args)
   {
    ThreadingDemo td = new ThreadingDemo();
    td.Display();
    Console.Read();
   }
 }
} 

/div>

No comments:

Post a Comment

Flag Counter