Print Even and Odd Numbers Using 2 Threads
There will be two threads such that one thread only prints even numbers while the other thread only prints odd numbers .
This problem is generally asked in interviews and its quite important with view of multithreading concept as it covers two main concept in the topic.
Here we will be achieving synchronization by using the synchronized methods . What this does is when one of the thread is executing the method then the other thread cannot execute that method .
Inter-thread communication allows synchronized threads to communicate with each other using a set of methods.The methods are wait, notify, and notifyAll.
Wait() causes the current thread to wait indefinitely until some other thread calls notify() or notifyAll() on the same object.
The code is pasted below . I have added some comments , please try to go through it , and if you have any doubts please feel free to comment.
import java.util.*;
import java.lang.*;
import java.io.*;
//Sub class of thread class
class EvenOddThread extends Thread{
Integer start;
Integer N;
Printer print;
Boolean isEven;
EvenOddThread(Integer start , Integer N, Printer print , Boolean isEven){
this.N = N;
this.start = start;
this.print = print;
this.isEven = isEven;
}
@Override
public void run(){
while(start <= N){
if(isEven)
print.evenPrinter(start);
else
print.oddPrinter(start);
start += 2;
}
}
}
//Helper Class
class Printer{
public volatile boolean isOdd = false; //This variable is Volatile since multiple threads are accessing it
//Method Synchronization using synchronized keyword
public synchronized void evenPrinter(int num){
if(!isOdd){
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println(num);
isOdd = false ;
notify();
}
public synchronized void oddPrinter(int num){
if(isOdd){
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println(num);
isOdd = true ;
notify();
}
}
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
Printer printerObj = new Printer();
EvenOddThread t1 = new EvenOddThread(1,10,printerObj,false); // Odd thread
EvenOddThread t2 = new EvenOddThread(2,10,printerObj,true); // Even thread
System.out.println("Thread execution starts.....");
t1.start(); //Starting thread1 which calls run method
t2.start(); //Starting thread2 which calls run method
}
}
Please UPVOTE if you like the post