Wednesday, 16 August 2017

Write a program in JAVA to print EVEN and ODD numbers within a range using multithreading.

To solve this problem we will be using one volatile variable as the variable will be shared between multiple threads.

We will have two threads even and odd. The logic is when even thread is executing odd thread will be suspended.

Suppose the Given input is: 10 
so output would be:
Odd Thread: 1
Even Thread: 2
Odd Thread: 3
Even Thread: 4
Odd Thread: 5
Even Thread: 6
Odd Thread: 7
Even Thread: 8
Odd Thread: 9
Even Thread: 10


Implemented Code:

 public class ThreadEvenOdd extends Thread{
    //Volatile keyword as this variable is going to be shared between multiple threads
    public volatile static int i=1;
    public Object lock;
    public ThreadEvenOdd(Object ob)
    {
        this.lock=ob;
    }
    public static void main(String[] args) {
        //Createing two threads even and Odd.
        Object object=new Object();
        ThreadEvenOdd even=new ThreadEvenOdd(object);
        ThreadEvenOdd odd=new ThreadEvenOdd(object);
        even.setName("Even Thread");
        odd.setName("Odd Thread");
        even.start();
        odd.start();      
    }
    @Override
    public void run()
    {
        while(i<=10)
        {
            if(i%2==0 && Thread.currentThread().getName().equalsIgnoreCase("Even Thread"))
            {
                synchronized(lock)
                {
                    System.out.println(Thread.currentThread().getName()+": "+i);
                    i++;
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            if(i%2==1 && Thread.currentThread().getName().equalsIgnoreCase("Odd Thread"))
            {
                synchronized(lock)
                {
                    System.out.println(Thread.currentThread().getName() + ": "+i);
                    i++;
                    lock.notify();
                }
            }
        }
    }
}
 



3 comments:

Use of Lamda Expression and Functional Interface in JAVA 8

In this blog, we are going to discuss one of the most important features of JAVA 8 which is Lamda Expression and Functional Interface. A...