Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wait and notify help needed

 
alfa mail
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai can any one please tell me what is wrong with this code .

public class ThreadA {

public static void main(String args[]){
ThreadA a=new ThreadA();
ThreadB b=new ThreadB();
b.start();
synchronized(ThreadB.class) {
try {
System.out.println("Waiting for b to complete...");
ThreadB.class.wait();
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
}
}
}

public class ThreadB extends Thread{
MysecondThread MysecondThread=new MysecondThread();
int total;
public void run(){
synchronized(this) {
for(int i=0;i<100;i++) {
total += i;
}
notify();
}
}

}



I am getting result as

Waiting for b to complete...

the thread is in waiting for long time its not notifying the waiting thread.

Help needed .
 
Vijitha Kumara
Bartender
Pie
Posts: 3918
10
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code only won't even compile with
MysecondThread MysecondThread=new MysecondThread();


If we ignore that and work on the rest(if that's what you expected)

ThreadB.class.wait();


You are waiting on a class not a specific object. Try changing it to b (with synchronized(b) instead synchronized(ThreadB.class) also).
 
Ajay Saxena
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have few questions..

1> Why do you need to synchronize anything at all in this problem?
I don't see the possibility of any race conditions in the context of the problem you have stated.

2> Why do you need an instance of ThreadA in the main() method of ThreadA?

3> Also what's this MysecondThread class for?

You can achieve your intended result by invoking the Thread.join() method as described below.


public class ThreadA{
public static void main(String args[]) {
ThreadB b = new ThreadB();
b.start();
try {
System.out.println("Waiting for b to complete...");
b.join();
} catch (InterruptedException e) {
}
System.out.println("Total is: " + b.total);
// }
}
}

class ThreadB extends Thread {

int total;
public void run() {
for (int i = 0; i < 100; i++) {
total += i;
}

}

[ August 28, 2008: Message edited by: Ajay Saxena ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic