This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes wait and notify help needed Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "wait and notify help needed" Watch "wait and notify help needed" New topic
Author

wait and notify help needed

alfa mail
Greenhorn

Joined: Aug 28, 2008
Posts: 1
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

Joined: Mar 24, 2008
Posts: 3817

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).


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Ajay Saxena
Ranch Hand

Joined: Nov 13, 2006
Posts: 154
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: wait and notify help needed
 
Similar Threads
notify(); doesn't work?
thread doubt
wait and notify problem from K&B.
Using wait/notify()
Lock Mechanism ?