javatechie

Print Even & Odd By Two Thread

Sep 21st, 2019
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. package com.javatechie.solution;
  2.  
  3. public class Even_And_Odd_Printer_By_Two_Thread implements Runnable {
  4.    
  5.     static int count = 1;
  6.     Object object;
  7.  
  8.     public EvenAndOddPrinter(Object object) {
  9.         this.object = object;
  10.     }
  11.  
  12.     @Override
  13.     public void run() {
  14.        
  15.         //loop your loop up to your desired limit (Here i want to print even and odd up to 10)
  16.         while (count <= 10) {
  17.            
  18.             //check if number is even
  19.             if (count % 2 == 0 && Thread.currentThread().getName().equals("even")) {
  20.                
  21.                 //synchronized object for single thread execution (to avoid data inconsistency)
  22.                 synchronized (object) {
  23.                     System.out.println(Thread.currentThread().getName() + "-" + count);
  24.                     count++;
  25.                     try {
  26.                         object.wait();
  27.                     } catch (InterruptedException e) {
  28.                         e.printStackTrace();
  29.                     }
  30.                 }
  31.             }
  32.             if (count % 2 != 0 && Thread.currentThread().getName().equals("odd")) {
  33.                 synchronized (object) {
  34.                     System.out.println(Thread.currentThread().getName() + "-" + count);
  35.                     count++;
  36.                     object.notify();
  37.                 }
  38.             }
  39.         }
  40.     }
  41.  
  42.     public static void main(String[] args) {
  43.         Object lock = new Object();
  44.         Runnable r1 = new EvenAndOddPrinter(lock);
  45.         Runnable r2 = new EvenAndOddPrinter(lock);
  46.         new Thread(r1, "even").start();
  47.         new Thread(r2, "odd").start();
  48.     }
  49. }
Add Comment
Please, Sign In to add comment