Showing posts with label MultithreadingExample. Show all posts
Showing posts with label MultithreadingExample. Show all posts

Thursday, 27 February 2014

Multithreading example for producer consumer problem for alternate numbers

Problem Statement:

Write a multithreading program which uses 2 threads. One threads prints odd numbers and other prints even numbers. The final output should print the numbers in sequence.

Solution:

1. Main.Java

public class Main {
   
    public static void main(String [] args){
        Monitor m=new Monitor();
        Thread task1=new Thread(new Task1(m));
        Thread task2=new Thread(new Task2(m));
        task1.start();
        task2.start();
      
    }

}

2. Monitor.java

public class Monitor {
    private boolean flag=true;

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
   

}


3. Task1.java

public class Task1 implements Runnable{
    private Monitor monitor;
   
   
    public Task1(Monitor monitor) {
        super();
        this.monitor = monitor;
    }


    @Override
    public void run() {
        for(int i=0; i<=10; i=i+2){          
        synchronized (monitor) {
            while(!monitor.isFlag()){
                try {
                    monitor.wait();
                    } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        System.out.println("Printing :"+i);
        monitor.setFlag(false);
        monitor.notifyAll();

              
                }
        }
      
    }

}

Task2.java

public class Task2 implements Runnable{
    private Monitor monitor;
   
   
    public Task2(Monitor monitor) {
        super();
        this.monitor = monitor;
    }


    @Override
    public void run() {
        for(int i=1; i<=10; i=i+2){           
        synchronized (monitor) {
            while(monitor.isFlag()){
                try {
                    monitor.wait();
                    } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
               
            }
        System.out.println("Printing :"+i);
                monitor.setFlag(true);
                monitor.notifyAll();
        }
        }
       
    }

}