Now a day's, a common question asked in interviews are threads. In this post we are going to learn how to implement two thread which is usedto display odd and even numbers.
In the following program, thread 1 prints even numbers and thread 2 prints odd numbers
EvenOddPrinter.java package com.becbe.threads;public class EvenOddPrinter implements Runnable { boolean isEven = false; Object lock; public EvenOddPrinter( boolean isEven, Object lock) { this.isEven = isEven; this.lock = lock; } @Override public void run() { System.out.println("Inside Run"); if(isEven) { printEven(); } else { printOdd(); } } private void printOdd() { synchronized (lock) { for (int i = 1; i < 100;) { lock.notify(); i = i + 2; try { lock.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } lock.notify(); System.out.println( i ); } } } private void printEven() { synchronized (lock) { lock.notify(); for (int i = 0; i < 100;) { i = i + 2; try { lock.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } lock.notify(); System.out.println( i ); } } } public static void main(String[] args) { Object lock = new Object(); Thread t1 = new Thread(new EvenOddPrinter(true, lock)); Thread t2 = new Thread(new EvenOddPrinter(false, lock)); t1.start(); t2.start(); }}

we can use atomicity feature of java for this kind of questions
ReplyDelete