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

How many bits is a float?

530


How do you sort a string in alphabetical order in java?

523


Explain about java sdk?

574


What is json parser in java?

605


What restrictions are placed on method overriding?

633






What happens if I remove static from main method?

515


Mention a package that is used for linked list class in java.

516


Why is it important to initialize a variable?

487


What is a boolean structure?

549


Can we force the garbage collection to run?

528


Differences between traditional programming language and object oriented programming language?

564


What does regex mean?

558


Can you call one constructor from another if a class has multiple constructors?

576


How do you define a parameter?

576


hi am an engineering student and my next plan is for ms in either in us or australia i got my passport but i dont know anything bout visa can u give brief idea 1)How to get prepared for visa and 2)How to apply for top universities and 3)How to pay the fee and so on These all are basic questions plz give me a clear idea

1455