Friday, 12 January 2018

Write a java program to print even and odd values in sequence using two threads with Synchronization, wait, notify and notifyAll.

print even and odd values in sequence using two threads with Synchronization, wait, notify and notifyAll. Wait() example,notify() method example, notifyAll() method example, how to use wait() method in java multithreading,how to use notify() method in java multithreading,how to use notifyAll() method in java multithreading,

package com.dashzin.Thread;
public class PrintEvenOdd {

        public static void main(String ... args){
        Printer print = new Printer();
        Thread t1 = new Thread(new TaskEvenOdd(print, 10,  false));
        Thread t2 = new Thread(new TaskEvenOdd(print, 10, true));
        t1.start();
        t2.start();
    }
        
}

class TaskEvenOdd implements Runnable {
    private int max;
    private Printer print;
    private boolean isEvenNumber;

    TaskEvenOdd(Printer print, int max, boolean isEvenNumber){
        this.print = print;
        this.max = max;
        this.isEvenNumber = isEvenNumber;
    }

    @Override
    public void run() {
        int number = isEvenNumber == true ? 2 : 1;
        while(number<= max){
            if(isEvenNumber){
                print.printEven(number);
            }   
            else {
                print.printOdd(number);
            }
            number+=2;
        }
        }
}

class Printer {
    boolean isOdd= false;
    synchronized void printEven(int number) {
        while(isOdd == false){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Even No:"+number);
        isOdd = false;
        notifyAll();
    }
    synchronized void printOdd(int number) {
        while(isOdd == true){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Odd No:"+number);
        isOdd = true;
        notifyAll();
    }
}


Output : 

Odd No:1
Even No:2
Odd No:3
Even No:4
Odd No:5
Even No:6
Odd No:7
Even No:8
Odd No:9
Even No:10



DashZin

Author & Editor

Has laoreet percipitur ad. Vide interesset in mei, no his legimus verterem. Et nostrum imperdiet appellantur usu, mnesarchum referrentur id vim.

1 comments: