write a code,
we have two thread, one is printing even no and other print the odd no.
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 |
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?
what is the replacement method of stop() of thread
Can an unreferenced object be referenced again?
what is hashmap& hashtable with example?
How do you use nextline in java?
Explain listiterator and methods in listiterator?
What is the main use of generics in java?
What best practices should you follow while writing multithreaded code in java?
Differentiate storage classes on the basis of their scope?
What about method local inner classes or local inner classes in java?
How do you declare a destructor in java?
Can java run on google chrome?