Sunday, March 9, 2014

Thread State


Thread State
The  thread  state  specifies  the  current  status  of  the  thread.  Sometimes,  the  thread automatically  switches  from  one state  to  another  state  automatically;  at  some other  times,  you can switch its state by using the methods offered by Thread class.
The  following  diagram  called  Thread  Life  Cycle  describes  the  different  states  of  a thread.
  1. Ready:  This is the initial state. The thread object is created.
  2. Running: The thread is currently being executed.
  3. Sleeping: The thread is temporarily paused. .NET framework offers automatic switching between Running and Sleeping states, when other threads are executed.
  4. Suspended:  The  thread is  temporarily  suspended  (paused).  It  will  be  continued,  when you call Resume() method.
  5. Dead: The thread was closed; it can‘t be restarted or continued.
Thread class methods:
  • thobj.Start() : This method starts-up the thread execution.
  • Thread.Sleep(mille sec) : This method puts the thread under Sleeping state, up to a certain no. of mille seconds. When  the  given  no.  of  mille  seconds are  completed,  automatically  the thread execution will be continued.
  • thobj.Suspend() : This  is  similar  to  Sleep()  method,  but  here,  no  time  limit  will  be  given.  That means whenever the Suspend() method is called, the thread will be put under Suspended state, until the Resume() method is called.
  • thobj.Resume() :  This  is  to  continue  the  thread  execution  that  is  under  Suspended  state.  This method won‘t work if the thread is not under Suspended state.
  • thobj.Abort() : This is close the thread execution completely, at any time. Once, if the Abort() method is called, the thread can‘t be started or resumed. This is the end of every thread life cycle
Program of Thread State
                                                                
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadLifeCycleDemo
{
class ThreadingDemo
{
 private void FirstMethod()
  {
   for (int i = 1; i <= 50; i++)
   {
    Console.Write("i=" + i + " ");
    Thread.Sleep(1000);
   }
  }
  private void SecondMethod()
  {
   for (int j = 1; j <= 50; j++)
   {
    Console.Write("j=" + j + " ");
    Thread.Sleep(1000);
    if (j == 20)
    th1.Suspend();
  else if (j == 30)
    th1.Resume();
   }
  }
  Thread th1, th2;
  public void Display()
   {
    th1 = new Thread(FirstMethod);
    th2 = new Thread(SecondMethod);
    th1.Start();
    th2.Start();
   }
  }
 class Program
 {
  static void Main(string[] args)
  {
   ThreadingDemo td = new ThreadingDemo();
   td.Display();
   Console.Read();
  }
 }
}

No comments:

Post a Comment

Flag Counter