gpt4 book ai didi

java, volatile 静态和同步 - 线程中的空异常

转载 作者:行者123 更新时间:2023-11-30 03:56:52 24 4
gpt4 key购买 nike

我定义了一个公共(public) 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();
}
}
}

最佳答案

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"

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

If I modify the definition to be public volatile static LinkedList, then I get an exception :

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

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

关于java, volatile 静态和同步 - 线程中的空异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22943122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com