简体   繁体   中英

Regarding wait and notify

I was developing the simple code related to wait & notify I have created two seprate classes , below are the classes

    class ThreadA {
 public static void main(String [] args) {
 Thread b = new Thread();
 b.start();

 synchronized(b) {
 try {
 System.out.println("Waiting for b to complete...");
 b.wait();
} catch (InterruptedException e) {}
 //System.out.println("Total is: " + b.totals);
 }
}
}

and the other one is ...





class ThreadB extends Thread {
public  int totals;

 public void run() {
     synchronized(this) {
     for(int i=0;i<100;i++) {
      totals += i;
      }
      notify();
      }
      }
     }

but inside class ThreadA, I am getting the complie time error when I am accessing the totals from b thread object that is ..

System.out.println("Total is: " + b.totals);

Please advise me how to correct it so that I can execute my code..!! thanks in advance ..!1

This is the immediate problem:

Thread b = new Thread();

You're never actually creating an instance of ThreadB . The type of b is only Thread , not ThreadB which is why the compiler can't resolve the totals identifier

Additionally:

  • Public fields are a really bad idea - use properties instead
  • Calling wait and notify on a Thread is a very bad idea, as the Thread class itself calls wait and notify .
  • You should usually implement Runnable instead of extending Thread , for better separation of concerns.
  • It would generally be better to call something on your class which knew to synchronize on a monitor which is only visible to that code, rather than synchronizing (and waiting for) a publicly visible monitor. It makes it easier to reason about your threading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM