Friday, July 31, 2015

Print even and odd numbers using threads in java - Java-fries



Print even and odd numbers using threads in java - Java-fries
Problem: How to print even and odd numbers using threads in Java? Two threads should be used to print numbers. One thread should print even numbers and other should print odd numbers. Numbers should be printed sequentially .i.e. 1, 2, 3, 4..
package com.javafries.thread;

public class EvenOddNumberPrinter {

private static class NumberPrinter {

// To check if even number is printed or not.
private boolean isEvenPrinted = true;

public void printOdd(int number) throws InterruptedException {
// Get a lock on NumberPrinter
synchronized (this) {

// Wait until even is not printed.
if (!isEvenPrinted)
wait();

System.out.println(number);

isEvenPrinted = false;

// Notify the other waiting thread which is waiting on
// NumberPrinter
// Other thread will get out of waiting state
notify();
}
}

public void printEven(int number) throws InterruptedException {
synchronized (this) {
if (isEvenPrinted)
wait();

System.out.println(number);
isEvenPrinted = true;
notify();
}
}
}

private static class OddNumberGenerator implements Runnable {
private NumberPrinter q;
private int max;

public OddNumberGenerator(NumberPrinter q, int max) {
this.q = q;
this.max = max;
}

@Override
public void run() {
for (int i = 1; i < max; i = i + 2) {
try {
q.printOdd(i);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
http://www.coderpanda.com/communication-between-threads-in-java/
private static class EvenNumberGenerator implements Runnable {
private NumberPrinter printer;
private int max;

public EvenNumberGenerator(NumberPrinter printer, int max) {
this.printer = printer;
this.max = max;
}

@Override
public void run() {
for (int i = 2; i <= max; i = i + 2) {
try {
printer.printEven(i);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}

public static void main(String[] args) {
int maxNumber = 10;
NumberPrinter printer = new NumberPrinter();

new Thread(new EvenNumberGenerator(printer, maxNumber)).start();
new Thread(new OddNumberGenerator(printer, maxNumber)).start();
}
}

public class EvenRunnable implements Runnable {
    private int number = 2;
    private Object shared = null;
    public EvenRunnable(Object object) {
        shared = object;
    }
    public void run() {
        while (number < 50) {
            synchronized (shared) {
                System.out.println("Even number =  " + number);
                number = number + 2;
                try {
                    Thread.sleep(500); //only to view sequence of execution
                    shared.notify();
                    shared.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class OddRunnable implements Runnable {
    int oddNumber = 1;
    private Object shared = null;
    public OddRunnable(Object object) {
        shared = object;
    }
    public void run() {
        while (oddNumber < 50) {
            synchronized (shared) {
                System.out.println("Odd number = " + oddNumber);
                oddNumber = oddNumber + 2;
                try {
                    Thread.sleep(500); // only to view the sequence of execution
                    shared.notify();
                    shared.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class Main {
    public Main(){
           }
    public static void main(String[] args) {
        Object shared = new Object();
        EvenRunnable evenRunnable = new EvenRunnable(shared);
        OddRunnable oddRunnable = new OddRunnable(shared);
        Thread evenThread = new Thread(evenRunnable, "evenThread");
        Thread oddThread = new Thread(oddRunnable, "oddThread");
        oddThread.start();
        evenThread.start();
    }
}

http://anujprashar.blogspot.com/2014/11/printing-odd-even-number-alternately.html
class Counter{
    //The int variable that is used by both threads.
    public int count = 1;
}

class EvenTask implements Runnable{
    private Counter counter;
   
    public EvenTask(Counter counter){
        this.counter = counter;
    }
   
    @Override
    public void run() {
        while (true) {
            synchronized (counter) {
                //If counter.num is odd then even thread will release lock and goes to wait state
                //so that odd thread can print.
                if(counter.count % 2!=0){
                    try {
                        counter.notify();
                        counter.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //Control will come here if odd thread has released lock
                //or if number is even.
                System.out.println(Thread.currentThread().getName()+"-"+counter.count);
                counter.count++;
                try {
                    Thread.sleep(200);//Some ms of sleep so that output is not very fast.
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class OddTask implements Runnable{
    private Counter counter;
   
    public OddTask(Counter counter){
        this.counter = counter;
    }
   
    @Override
    public void run() {

        while (true) {
            synchronized (counter) {
                //If counter.num is even then odd thread will release lock and goes to wait state
                //so that even thread can print.
                if(counter.count % 2==0){
                    try {
                        counter.notify();
                        counter.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //Control will come here if even thread has released lock
                //or if number is odd.
                System.out.println(Thread.currentThread().getName()+"-"+counter.count);
                counter.count++;
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
http://www.somanyword.com/2013/11/printing-even-and-odd-using-two-threads-in-java/
public class EvenOddTest {

 public static void main(String[] args) {

  EvenOddPrinter printer = new EvenOddPrinter();

  Thread even = new Thread(new PrintTask(printer, 100, true));
  Thread odd = new Thread(new PrintTask(printer, 100, false));

  odd.start();
  even.start();
 }

}

class PrintTask implements Runnable{

 int max = 0;
 boolean isEven = false;
 EvenOddPrinter p = null;
 int num = 0;

 public PrintTask(EvenOddPrinter p, int max, boolean isEven) {
  this.p = p;
  this.max = max;
  this.isEven = isEven;
 }

 public void run() {

  num = (isEven) ? 2 : 1; 

  while (num <= max) {

   if (isEven){ 
    p.printEven(num);
   }
   else {
    p.printOdd(num);
   }

   num += 2;
  }

 }
}

class EvenOddPrinter {
 boolean isOdd = false;

 public synchronized void printEven(int number) {

  while (!this.isOdd) {
   try {
    wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  System.out.println("Even Number : " + number);
  this.isOdd = false;
  notify();
 }

 public synchronized void printOdd(int number) {

  while (this.isOdd) {
   try {
    wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  System.out.println("Odd Number : " + number);
  this.isOdd = true;
  notify();
 }
}
http://rohandhapodkar.blogspot.com/2012/04/print-odd-and-even-numbers-using-two.html
Read full article from Print even and odd numbers using threads in java - Java-fries

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts