【发布时间】:2015-05-08 07:03:03
【问题描述】:
public class Chicks {
synchronized void yacks(long id)
{
for(int x = 1; x<3; x++)
{
System.out.println(id + " ");
Thread.yield();
}
}
}
class ChickYacks implements Runnable
{
Chicks c; // No exception if I declare it as static
public static void main(String[] args) {
new ChickYacks().go();
}
public void run()
{
c.yacks(Thread.currentThread().getId()); //Throws a Nullpointer exceptin
}
void go()
{
c = new Chicks();
new Thread(new ChickYacks()).start();
new Thread(new ChickYacks()).start();
}
}
为什么会在run method() 中抛出 Nullpointer 异常。在我看来一切都很好。当我将Chicks 'c' 声明为静态但我不明白为什么?
【问题讨论】:
-
请注意,这与多线程无关。您只是在创建对象,忘记为这些对象的字段分配非空值,然后在此空字段上调用方法。
标签: java multithreading scjp ocpjp