Explain Multithreading?

In this blog, we create two threads: thread1 and thread2. Each thread is assigned a different task: CountNumbers and PrintMessage. Both tasks involve printing some output with a delay of 1 second using Thread.Sleep to simulate work.

  • Multi-threading refers to the ability to execute multiple threads of code concurrently within a single process.
  • Multi-threading allows you to perform multiple tasks simultaneously, such as downloading data while displaying a progress bar.
  • To create multithreaded application in C#, we need to use SYSTEM.THREADING namespace.


using System; using System.Threading; public class Program { public static void Main() { // Create two threads and assign work to them Thread thread1 = new Thread(CountNumbers); Thread thread2 = new Thread(PrintMessage); // Start the threads thread1.Start(); thread2.Start(); // Wait for the threads to complete thread1.Join(); thread2.Join(); Console.WriteLine("Main thread finished"); } public static void CountNumbers() { for (int i = 1; i <= 5; i++) { Console.WriteLine($"Count: {i}"); Thread.Sleep(1000); // Simulate some work } } public static void PrintMessage() { for (int i = 1; i <= 5; i++) { Console.WriteLine($"Message: Hello {i}"); Thread.Sleep(1000); // Simulate some work } } }

The Main method starts the threads using Start(), which initiates their execution. After starting the threads, we use Join() to wait for each thread to complete before proceeding. This ensures that the main thread waits for the other threads to finish their work.

When the program runs, CountNumbers and PrintMessage are executed concurrently in separate threads. Each thread prints its respective output, and the delays introduced by Thread.Sleep simulate some processing time. As a result, the messages and counts may interleave or appear in a non-sequential order due to the parallel execution.

Finally, the main thread prints "Main thread finished" after waiting for the completion of the other threads.

The example demonstrates the concurrent execution of multiple threads, where CountNumbers and PrintMessage run simultaneously, potentially improving performance and responsiveness. Multi-threading allows different parts of the program to execute concurrently, making efficient use of available system resources.

Post a Comment

Previous Post Next Post