Even and Odd number sequence with 2 threads in C# Program

(Last Updated On: March 4, 2017)

C# multithreading Interview Question: Using two threads print even and odd number in sequence. One thread prints even numbers and another thread prints odd numbers.

Thread T1 : 0,2,4,6…

Thread T2 :1,3,5,7…

Output: 0, 1,2,3,4,5,6,7…

Answer: To solve this problem let’s use signalling mechanism using  wait () and pulse () method of Monitor class in C#. Other mechanism we can use AutoResetEvent or something.

In below C# program example, we will use wait () method to make the thread waiting and pulse () method to signal other thread.

Use cases:

Even thread will start first to print the number on console.
Even thread will signal odd thread to print the number using pulse() method.
Even thread will wait for signal from odd thread using wait() method.

Same odd thread should do.

Caution:

Since both odd and even threads are sharing console to print the number we need to put a lock over console IO.

Since, we want the sequence should be started with even number, even thread must run first. So, after we will start even thread we need to pause for a moment before starting odd thread using Sleep () method to avoid any chance to start odd thread first or else sequence will be like below

1 0 3 2 5 4 7 6 9 8

Note that for correct sequence even thread must start first.

0 1 2 3 4 5 6 7 8 9 10

C# Program with comments: