【发布时间】:2024-08-07 09:35:02
【问题描述】:
我定义了一个公共的 volatile LinkedList 与一些线程共享,我在 main() 中同步它,它是静态的...... 所以我得到一个编译错误:“无法引用非静态字段”
如果我将定义修改为 public volatile static LinkedList,那么我会得到一个异常:
Exception in thread "filteringThread" java.lang.NullPointerException
at com.swimtechtest.swimmerbench.FilteringThread.run(FilteringThread.java:39)
这是我的代码的一部分
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();
}
}
}
【问题讨论】:
-
samplings在您的线程中必须为空。你在哪里设置的?
标签: java multithreading volatile