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

wait and notify help needed

alfa mail

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();
synchronized(ThreadB.class) {
try {
System.out.println("Waiting for b to complete...");
} catch (InterruptedException e) {}
System.out.println("Total is: " +;

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;


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

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)


You are waiting on a class not a specific object. Try changing it to b (with synchronized(b) instead synchronized(ThreadB.class) also).

[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();
try {
System.out.println("Waiting for b to complete...");
} catch (InterruptedException e) {
System.out.println("Total is: " +;
// }

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:
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 ?