Print Even and Odd numbers using two threads in java example code

package com.fuck;

public class EvenOrOddWithTwoThreads {

public static void main(String[] args) {
SharedPrinter sp= new SharedPrinter();
Thread t1= new Thread(new EvenNumProducer(sp,10));
Thread t2= new Thread(new OddNumProducer(sp,10));

t1.start();
    t2.start();
}

}

class SharedPrinter {

boolean evenFlag=false;

public void printEvenNumber(int num){
synchronized (this) {
while(!evenFlag){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
   System.out.println("Even : "+num);
evenFlag=false;
notify();
}
}

//Method for printing odd numbers
public void printOddNum(int num){
  synchronized (this) {
   while(evenFlag){
    try {
     wait();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
   System.out.println("Odd "+num);
   evenFlag = true;
   notify();
   
  }
}
}
class EvenNumProducer implements Runnable{
    SharedPrinter sp;
    int index;
    EvenNumProducer(SharedPrinter sp, int index){
        this.sp = sp;
        this.index = index;
    }
    @Override
    public void run() {
        for(int i = 2; i <= index; i = i+2){
            sp.printEvenNumber(i);
        }
        
    }
    
}

class OddNumProducer implements Runnable{
    SharedPrinter sp;
    int index;
    OddNumProducer(SharedPrinter sp, int index){
        this.sp = sp;
        this.index = index;
    }
    @Override
    public void run() {
        for(int i = 1; i <= index; i = i+2){
            sp.printOddNum(i);
        }
    }
}

Search This Blog

All the rights are reserved to this blog is belongs to me only.. Powered by Blogger.