Below I am giving you my code which I wrote to print even number using even thread and odd number using odd thread sequentially.
Could anyone please validate my code whether it is correct way of doing it or not? I am getting correct result, but I just want to make sure whether I am doing it in correct way or not.
public class PrintNumberUsingThread {
public static void main(String[] args) {
PrintNumberUsingThread example = new PrintNumberUsingThread();
PNThread pnThread = example.new PNThread(10);
new Thread(pnThread).start();
new Thread(pnThread).start();
}
class PNThread implements Runnable {
private int number = 0;
private int maxNumber;
public PNThread(int maxNumber) {
this.maxNumber = maxNumber;
}
@Override
public void run() {
while (number <= maxNumber) {
synchronized (this) {
String threadName = Thread.currentThread().getName();
if (number <= maxNumber) {
boolean even = threadName.contains("0") && number % 2 == 0;
boolean odd = threadName.contains("1") && number % 2 != 0;
if (even || odd) {
System.out.println(threadName + "-" + number++);
this.notifyAll();
} else {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}