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:
wait
and notify
on a Thread
is a very bad idea, as the Thread
class itself calls wait
and notify
. Runnable
instead of extending Thread
, for better separation of concerns.
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.