Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...


write a code,
we have two thread, one is printing even no and other print the odd no.



write a code, we have two thread, one is printing even no and other print the odd no...

Answer / umeshag89

public class EvenOdd {
public static void main(String[] args) {
final Printer printer = new Printer();
new Thread(new Runnable() {
@Override
public void run() {
int i = 1;
while (i < 100) {
printer.printOdd(i);
i = i + 2;
}
}
}).start();

new Thread(new Runnable() {
@Override
public void run() {
int i = 2;
while (i < 100) {
printer.printEven(i);
i = i + 2;
}
}
}).start();
}

static class Printer {
boolean isOdd = true;

synchronized public void printOdd(int number) {
while (!isOdd) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(number + " ");
isOdd = false;
notify();
}

synchronized public void printEven(int number) {
while (isOdd) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(number + " ");
isOdd = true;
notify();
}
}
}

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More Core Java Interview Questions

Why would you desing a J2EE application so user data is entered by way of a JSP page and managed by an underlying Java Beans class?

5 Answers   Adobe,


what is the replacement method of stop() of thread

8 Answers   IBM, TCS,


Can an unreferenced object be referenced again?

0 Answers  


what is hashmap& hashtable with example?

1 Answers   CTS,


How do you use nextline in java?

0 Answers  


Explain listiterator and methods in listiterator?

0 Answers  


What is the main use of generics in java?

0 Answers  


What best practices should you follow while writing multithreaded code in java?

0 Answers  


Differentiate storage classes on the basis of their scope?

0 Answers   Fidelity,


What about method local inner classes or local inner classes in java?

0 Answers  


How do you declare a destructor in java?

0 Answers  


Can java run on google chrome?

0 Answers  


Categories