【问题标题】:java , volatile static and synchronized - null exception in threajava , volatile static 和 synchronized - 线程中的空异常
【发布时间】: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


【解决方案1】:

我定义了一个公共的 volatile LinkedList 与一些线程共享, 我在静态的 main() 中同步它......所以我得到一个 编译错误:“无法引用非静态字段”

这与 volatile 或同步无关,这是因为您在静态 main() 方法中访问实例变量 samplings

如果我将定义修改为 public volatile static LinkedList, 然后我得到一个例外:

 Exception in thread "filteringThread" java.lang.NullPointerException
at com.swimtechtest.swimmerbench.FilteringThread.run(FilteringThread.java:39)

这是因为,FilteringThread 中的实例变量 samplings 从未分配给 List 类型的对象。默认赋值为null

【讨论】:

    最近更新 更多