Please review the code below where thread Odd prints all odd numbers from 1 to 9 and thread Even prints all even numbers from 2 to 8. I tested it and it works but can we improve it from design or performance perspective?
To print odd
public class Odd implements Runnable{
private Monitor sharedObject;
public Odd(Monitor monitor){
this.sharedObject = monitor;
}
@Override
public void run() {
try {
printOdd();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void printOdd() throws InterruptedException {
synchronized(sharedObject){
for(int i=1; i< 10; i++){
if(i%2!=0){
while(!sharedObject.isOdd()){
sharedObject.wait();
}
System.out.println("Odd: "+ i);
sharedObject.setOdd(false);
sharedObject.notifyAll();
}
}
}
}
To print even
public class Even implements Runnable{
private Monitor sharedObject;
public Even(Monitor monitor){
this.sharedObject = monitor;
}
@Override
public void run() {
try {
printEven();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void printEven() throws InterruptedException {
synchronized(sharedObject){
for(int i=1; i< 10; i++){
if(i%2==0){
while(sharedObject.isOdd()){
sharedObject.wait();
}
System.out.println("Even: "+ i);
sharedObject.setOdd(true);
sharedObject.notifyAll();
}
}
}
}
Monitor class
public class Monitor {
private volatile boolean isOdd;
public boolean isOdd() {
return isOdd;
}
public void setOdd(boolean isOdd) {
this.isOdd = isOdd;
}
}