truekiller :
I tried to print Odd and Even Numbers Alternatively using two thread. But the program entered a deadlock. I am not able to understand why it is entering a deadlock. In debug mode, program behaves differently. It prints 1 2 then deadlock. This behavior is unexpected.
Expected Output
1
2
3
4
odd thread ends here
even thread ends here
main thread ends here
Current Output
1
2
3
4
odd thread ends here
(Deadlock)
Here is the java code
public class PrintSequence {
public static void main(String[] args) {
EvenOddPrinter printer = new EvenOddPrinter(false, 1, 4);
Thread odd = new Thread(new Runnable() {
@Override
public void run() {
printer.printOdd();
}
});
Thread even = new Thread(new Runnable() {
@Override
public void run() {
printer.printEven();
}
});
odd.start();
even.start();
try {
odd.join();
System.out.println("odd thread ends here");
even.join();
System.out.println("even thread ends here");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main thread ends here");
}
}
class EvenOddPrinter {
private boolean isEven;
private int index;
private int maxNumber;
public EvenOddPrinter(boolean isEven, int index, int maxNumber) {
super();
this.isEven = isEven;
this.index = index;
this.maxNumber = maxNumber;
}
public synchronized void printOdd () {
while(index < maxNumber) {
if(!isEven) {
System.out.println(index);
index++;
isEven = true;
notify();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void printEven() {
while(index <= maxNumber) {
if(isEven) {
System.out.println(index);
index++;
isEven = false;
notify();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Can someone help me in fixing this?
WJS :
When odd finishes, it never notifies the even thread. So do this.
public synchronized void printOdd () {
while(index < maxNumber) {
if(!isEven) {
System.out.println(index);
index++;
isEven = true;
notify();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notify(); // add a notify here
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=356185&siteId=1