【发布时间】:2015-04-06 13:10:40
【问题描述】:
我正在实现一个简单的 SimpleInterThreadCommunication 示例,并使用了等待和通知。
我在 InterThread 类中得到一个错误,谁能解释原因
public class InterThread
{
public static void main(String s[])throws InterruptedException
{
Thread b=new Thread();
b.start();
Thread.sleep(10);
synchronized (b)
{
System.out.println("Main thread trying to call wait");
b.wait();
System.out.println("Main thread got notifies");
System.out.println(b.total); //error here total cannot be resolved to a field
}
}
}
class ThreadB extends InterThread
{
int total=0;
public void run()
{
synchronized(this)
{
System.out.println("child thread got notifies");
for(int i=0;i<3;i++)
{
total=total+i;
}
System.out.println("child thread ready to give notification");
this.notify();
}
}
}
【问题讨论】:
-
这是因为您的对象 b 属于线程类,并且总字段未在线程类中隐式定义,而是您在 ThreadB 类中定义了变量 b。因此它无法解析为变量。
-
因为
Thread没有名为b的public字段。 -
顺便说一句。使用 java.util.concurrent 中的类可以以更简单、更可靠的方式完成线程通信。例如LinkedTransferQueue
标签: java multithreading wait notify