• Post Reply Bookmark Topic Watch Topic
  • New Topic

Deadlock with Java Threads  RSS feed

 
sai praveen anumukonda
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have 2 threads. One thread prints odd numbers and the second thread prints even numbers. Now, I have to execute the threads alternatively so that i can output 1,2,3,4,5,6,.....

I have written a program for this and this is resulting in a deadlock. The output is also not desired. When i run the program i get 1 2 4 3 5 6 8 7 9 10 11 13 12 15 17 14....

Can someone explain what is the problem with the code and how to rectify it?

class BooleanObject {
boolean flag;
BooleanObject(boolean flag) {
this.flag = flag;
}
}
class EvenThread extends Thread {
Object lock;
BooleanObject flagObj;
EvenThread(Object o, BooleanObject flag) {
lock = o;
this.flagObj = flag;
}
public void run() {
for (int i=2;i<100;i+=2) {
synchronized(lock) {
if (flagObj.flag == false) {
flagObj.flag = true;
lock.notify();
}
else {
try {
while (flagObj.flag == true) {
lock.wait();
}
}
catch (InterruptedException e) {

}
}
System.out.println(i);
}
}
}
}

class OddThread extends Thread {
Object lock;
BooleanObject flagObj;
OddThread(Object o, BooleanObject flag) {
lock = o;
this.flagObj = flag;
}
public void run() {
for (int i=1;i<100;i+=2) {
synchronized(lock) {
if (flagObj.flag == true) {
flagObj.flag = false;
lock.notify();
}

else {
try {
while(flagObj.flag == false) {
lock.wait();
}
}
catch (InterruptedException e) {

}
}
System.out.println(i);
}
}
}
}

public class EvenOddThreads {
public static void main(String[] args) {
Object obj = new Object();
BooleanObject flagObj = new BooleanObject(true);
EvenThread et = new EvenThread(obj,flagObj);
OddThread ot = new OddThread(obj,flagObj);

et.setName("even thread");
ot.setName("odd thread");

et.start();
ot.start();
}
}
 
Henry Wong
author
Sheriff
Posts: 23280
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Please use code tags -- your code is not readable without formatting.

Henry
 
Henry Wong
author
Sheriff
Posts: 23280
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I can see at least two issues....

First, there are cases where you release the thread (but not in the wait() method). If a notification is sent during this time, the notification will be lost -- and presumingly is the cause of your "deadlock".

Second, you set the flag and sent the notification before you print the result. This means, it is possible for the other thread to see the changed flag (without even doing a wait) and print the next number.

Henry
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!