Saturday, December 19, 2015

Printing Even and Odd using two Threads



http://www.zrzahid.com/process-threads-and-synchronization/
Given n, print numbers from zero to n sequentially using two threads such that one thread prints only odds and other prints only evens.

https://www.quora.com/How-do-you-write-a-multithreaded-program-where-the-first-thread-prints-are-an-odd-no-and-the-second-thread-prints-are-an-even-no-alternatively
http://netjs.blogspot.com/2016/04/print-odd-even-numbers-using-threads-wait-notify.html
 public static void main(String[] args) {
  // shared class object
  SharedPrinter sp = new SharedPrinter();
  // creating two threads
  Thread t1 = new Thread(new EvenNumProducer(sp, 10));
  Thread t2 = new Thread(new OddNumProducer(sp, 10));
  // starting threads
  t1.start();
  t2.start();
 }

}
// Shared class used by both threads
class SharedPrinter{
 boolean evenFlag = false;
 
 //Method for printing even numbers
 public void printEvenNum(int num){
  synchronized (this) {
    // While condition as mandated to avoid spurious wakeup
   while(!evenFlag){
    try {
     //asking current thread to give up lock
     wait();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   System.out.println(num);
   evenFlag = false;
   // Wake up thread waiting on this monitor(lock)
   notify();
   
  }
  
 }
 
 //Method for printing odd numbers
 public void printOddNum(int num){
  synchronized (this) {
    // While condition as mandated to avoid spurious wakeup
   while(evenFlag){
    try {
     //asking current thread to give up lock
     wait();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   System.out.println(num);
   evenFlag = true;
   // Wake up thread waiting on this monitor(lock)
   notify();
   
  }
 }
}

// Thread Class generating Even numbers
class EvenNumProducer implements Runnable{
    SharedPrinter sp;
    int index;
    EvenNumProducer(SharedPrinter sp, int index){
        this.sp = sp;
        this.index = index;
    }
    @Override
    public void run() {
        for(int i = 2; i <= index; i = i+2){
            sp.printEvenNum(i);
        }
        
    }
    
}

//Thread Class generating Odd numbers
class OddNumProducer implements Runnable{
    SharedPrinter sp;
    int index;
    OddNumProducer(SharedPrinter sp, int index){
        this.sp = sp;
        this.index = index;
    }
    @Override
    public void run() {
        for(int i = 1; i <= index; i = i+2){
            sp.printOddNum(i);
        }
    }
}
http://netjs.blogspot.com/2016/04/print-odd-even-numbers-using-threads-semaphore.html
public class EvenOddSem {

 public static void main(String[] args) {
    SharedPrinter sp = new SharedPrinter();
    // Starting two threads
           ExecutorService executor = Executors.newFixedThreadPool(2);
           executor.execute(new EvenNumProducer(sp, 10));
           executor.execute(new OddNumProducer(sp, 10));
           executor.shutdown();
 }

}

//Shared class used by both threads
class SharedPrinter{
 boolean evenFlag = false;
 // 2 semaphores 
        Semaphore semEven = new Semaphore(0);
        Semaphore semOdd = new Semaphore(1);
 
 //Method for printing even numbers
 public void printEvenNum(int num){
  try {
   semEven.acquire();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println(num);
  semOdd.release(); 
 }
 
 //Method for printing odd numbers
 public void printOddNum(int num){
  try {
   semOdd.acquire();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println(num);
  semEven.release();
   
 }
}

//Thread Class generating Even numbers
class EvenNumProducer implements Runnable{
    SharedPrinter sp;
    int index;
    EvenNumProducer(SharedPrinter sp, int index){
        this.sp = sp;
        this.index = index;
    }
    @Override
    public void run() {
        for(int i = 2; i <= index; i = i+2){
            sp.printEvenNum(i);
        }
        
    }
    
}

//Thread Class generating Odd numbers
class OddNumProducer implements Runnable{
    SharedPrinter sp;
    int index;
    OddNumProducer(SharedPrinter sp, int index){
        this.sp = sp;
        this.index = index;
    }
    @Override
    public void run() {
        for(int i = 1; i <= index; i = i+2){
            sp.printOddNum(i);
        }
    }
} 

==> not good, use wait, notify or
public class ThreadTest{
 private final Object lock = new Object();
 private int cur;
 private final int max;
 
 public ThreadTest(int n){
  this.max = n;
 }
 
 protected class PrintThread implements Runnable {
  private final int turn;
  
  public PrintThread(int turn){
   this.turn = turn;
  }

  @Override
  public void run() {
   while(true){
    try {
     Thread.sleep(10);
    } catch (InterruptedException e1) {
     e1.printStackTrace();
    }
    //get access to intrinsic lock of the ThreadTest class to access it's shared resources in synchronized manner
    //synchronized (ThreadTest.class) {
    //or get access to a explicit lock 
    synchronized (lock) { 
     if(cur > max){
      return;
     }
     
     if(cur%2 == turn){
      System.out.println("Thread "+this.turn+": "+cur++);
     }
    }
   }
  }
 }
 
 public void print() throws InterruptedException{
  ExecutorService pool = Executors.newFixedThreadPool(2);
  pool.execute(new PrintThread(0));
  pool.execute(new PrintThread(1));
  pool.shutdown();
 }
 
 public static void main(String args[]) throws InterruptedException{
  ThreadTest tt = new ThreadTest(20);
  tt.print();
 }
}

http://www.java-fries.com/2015/06/print-even-and-odd-numbers-using-threads-in-java/
    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();
            }
        }

http://www.careercup.com/question?id=19460664
public class ThreadevenOdd implements Runnable {
    private final boolean isEven;
    private final int count;
    static Semaphore oddSem = new Semaphore(1);
    static Semaphore evenSem = new Semaphore(0);
    ThreadevenOdd(final boolean flag, final int c) {
        isEven = flag;
        count = c;
    }
    @Override
    public void run() {
        if (isEven) {
            try {
                printEven(count);
            } catch (final InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            try {
                printOdd(count);
            } catch (final InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private void printOdd(final int count) throws InterruptedException {
        int c = 1;
        for (int i = 0; i < count; i++) {
            oddSem.acquire(1);
            System.out.println(c);
            c = c + 2;
            evenSem.release(1);
        }
    }

    private void printEven(final int count) throws InterruptedException {
        int c = 2;
        for (int i = 0; i < count; i++) {
            evenSem.acquire(1);
            System.out.println(c);
            c = c + 2;
            oddSem.release(1);
        }
    }
    public static void main(final String[] args) {
        final Thread a = new Thread(new ThreadevenOdd(true, 20));
        final Thread b = new Thread(new ThreadevenOdd(false, 20));
        a.start();
        b.start();

    }

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