C# – Define Custom Thread

Define Custom thread:

  • We need to pass the method(thread logic) as an argument by starting the new Thread as follows
    • Thread t = new Thread(new ThreadStart(method name));

Thread Life Cycle: Every thread has undergone different states in its Life.

  1. New State: Thread object created but not yet started.
  2. Runnable State: Thread waits in queue until memory allocated to run.
  3. Running State: Threads running independently once they started.
  4. Blocked State: The thread is still alive, but not eligible to run.
  5. Terminated State: A thread terminates either by complete process or by occurrence of error
using System;
using System.Threading;
public class Program
{
            static void Main(string[] args)
            {
                        Thread t1 = new Thread(new ThreadStart(First.print1to10));
                        Thread t2 = new Thread(new ThreadStart(Second.print10to1));
                        t1.Start();
                        t2.Start();
            }
}
public class First
{
            public static void print1to10()
            {
                        for (int i=1; i<=10; i++)
                        {
                                    Console.WriteLine(“i value : ” + i);
                                    Thread.Sleep(1000);
                        }
            }
}
public class Second
{
            public static void print10to1()
            {
                        for(int j=10; j>=1; j–)
                        {
                                    Console.WriteLine(“j value : ” + j);
                                    Thread.Sleep(1000);
                        }
            }
}
Scroll to Top