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.

Answer Posted / 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       View All Answers


Please Help Members By Posting Answers For Below Questions

Where is java located?

1124


What is difference between array and arraylist in java?

1040


Which keyword specify that a variable is effectively final ?

1053


How many characters is 2 bytes?

1042


What are the types of casting?

1119


Can we call virtual funciton in a constructor ?

2239


What is compiler and what its output.

1202


What are the two parts of a conditional statement?

997


How to change value in arraylist java?

1253


Explain abstract class in java?

1131


Name few "optional" classes introduced with java 8 ?

1187


What does the “final” keyword mean in front of a variable? A method? A class?

1038


How do you check if a number is a perfect square?

1036


What is a singleton in genetics?

1129


What is difference between local variable and global variable?

1084