我正在开发与wait¬ify相关的简单代码我创建了两个seprate类,下面是类
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是在ThreadA类中,当我从b线程对象访问总计时,我得到了complie时间错误.
System.out.println("Total is: " + b.totals);
Run Code Online (Sandbox Code Playgroud)
请告诉我如何纠正它,以便我可以执行我的代码.. !! 在此先感谢..!1
这是当前的问题:
Thread b = new Thread();
Run Code Online (Sandbox Code Playgroud)
你永远不会真正创建一个实例ThreadB.b只是类型Thread,而不是ThreadB编译器无法解析totals标识符的原因
另外:
wait和notifyon Thread是一个非常糟糕的主意,因为Thread类本身调用wait和notify.Runnable而不是扩展Thread,以便更好地分离关注点.