[英]java , volatile static and synchronized - null exception in threa
I defined a public volatile LinkedList to be shared with some threads, and I synchronize it within main() which is static... so I get a compile error : " cannot make a reference to a non static field" 我定义了一个公共的易失性LinkedList与某些线程共享,并在main()中将其同步,这是静态的...因此我收到了编译错误:“无法引用非静态字段”
If I modify the definition to be public volatile static LinkedList, then I get an exception : 如果我将定义修改为公共易失性静态LinkedList,则会出现异常:
Exception in thread "filteringThread" java.lang.NullPointerException
at com.swimtechtest.swimmerbench.FilteringThread.run(FilteringThread.java:39)
here is part of my code 这是我的代码的一部分
public class SwimmerBench{
...
public volatile LinkedList<InterpolatedEvent> samplings = new LinkedList<InterpolatedEvent>();
...
public static void main(String args[]) throws IOException {
...
InterpolatedEvent event = createInterpolatedEvent(fields);
synchronized(samplings){
samplings.add(event);
samplings.notifyAll();
}
...
}
}
======
public class FilteringThread extends Thread {
LinkedList<InterpolatedEvent> samplings;
public void run() {
System.out.println("Running " + threadName );
while(running ) {
try {
synchronized(samplings) { // <= exception error line 39
InterpolatedEvent event = samplings.getLast();
samplings.notifyAll();
}
}
}
I defined a public volatile LinkedList to be shared with some threads, and I synchronize it within main() which is static... so I get a compile error : " cannot make a reference to a non static field"
我定义了一个公共的易失性LinkedList与某些线程共享,并在main()中将其同步,这是静态的...因此我收到了编译错误:“无法引用非静态字段”
It's not related to volatile or synchronization, it's because you are accessing instance variable samplings
in static main()
method. 它与volatile或同步无关,因为您正在以静态
main()
方法访问实例变量samplings
。
If I modify the definition to be public volatile static LinkedList, then I get an exception :
如果我将定义修改为公共易失性静态LinkedList,则会出现异常:
Exception in thread "filteringThread" java.lang.NullPointerException at com.swimtechtest.swimmerbench.FilteringThread.run(FilteringThread.java:39)
This is because, your instance variable samplings
in FilteringThread
is never assigned to an object of type List
. 这是因为,您在
FilteringThread
实例变量samplings
永远不会分配给List
类型的对象。 It's assigned by default null 默认分配为null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.