I want to develop an application that contains two threads thread1 and thread2. Thread 1 has to print even numbers upto 50 and thread 2 has to print odd numbers upto 50. And both threads should communicate such that the printing oreder should be 1,2, 50. I tried the following code. How to communicate between EvenThread and OddThread
public class TestPrint{
public static void main(String[] args) {
EvenThread et=new EvenThread();
OddThread ot=new OddThread();
et.start();
ot.start();
}
}
class EvenThread extends Thread{
int even=0;
@Override
public void run() {
synchronized(this){
while(even<50){
System.out.println(even);
even=even+2;
try {
this.wait();
notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class OddThread extends Thread{
int odd=1;
@Override
public void run() {
synchronized(this){
while(odd<50){
System.out.println(odd);
odd=odd+2;
try {
this.wait();
notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}