NullPointerException,在实例化数组的所有成员后枚举数组时?

NullPointerException when enumerating array after instancing all of its members?

提问人:BRHSM 提问时间:12/30/2020 最后编辑:BohemianBRHSM 更新时间:2/21/2021 访问量:52

问:

我正在处理一段涉及线程的代码,我已经设置了以下 for 循环来实例化它们:

for (Buyer buyer : buyers) {
    isPrime = (rand.nextInt(10) + 1 < 3);
    buyer = new Buyer(warehouse,
                      isPrime,
                      "buyer" + ++i);
    buyer.start();
    System.out.println("started buyer: " + i);
}

之后,我实例化了一些其他线程,然后再次加入这些买方线程以等待程序完成:

System.out.println("Joining buyers. ");
for (Buyer buyer : buyers) {
    buyer.join();
    System.out.println("Joining thread: " + buyer.getName());
}

当我运行我的程序时,我在以下行得到 1 个 NullPointerException:所有线程都完成了执行,但似乎没有一个线程想在此时加入。这是怎么回事?buyer.join();

以下是买家线程的代码:

import java.util.Random;

public class Buyer extends Thread{
    private int packsBought = 0;
    private boolean isPrime;
    private Random rand;
    private Warehouse warehouse;

    public Buyer(Warehouse warehouse, Boolean isPrime, String name) {
        super(name);
        this.isPrime = isPrime;
        this.rand = new Random();
        this.warehouse = warehouse;
    }
    
    public void run() {
        while(this.packsBought < 10) {
            try {
                Thread.sleep(this.rand.nextInt(49) + 1);
            } catch (InterruptedException ex) {
                
            }
            Order order = new Order(this.rand.nextInt(3)+ 1, 
                                    this, 
                                    this.isPrime);
            this.warehouse.placeOrder(order);
        }
        System.out.println("Thread: " + super.getName() + " has finished.");
    }

    public int getPacksBought() {
        return this.packsBought;
    }

    public void setPacksBought(int packsBought) {
        this.packsBought = packsBought;
    }

    public boolean isPrime() {
        return isPrime;
    }  
}
Java 多线程 异常 并行处理 NullPointerException

评论


答:

1赞 dreamcrash 12/30/2020 #1

问题在于:

for (Buyer buyer : buyers) {
    isPrime = (rand.nextInt(10) + 1 < 3);
    buyer = new Buyer(warehouse,          // <--- this is wrong 
                      isPrime,
                      "buyer" + ++i);
    buyer.start();
    System.out.println("started buyer: " + i);
}

您并没有真正初始化 List 中的元素。这:buyers

buyer = new Buyer(warehouse,
                          isPrime,
                          "buyer" + ++i);

不会更改保存在列表中的引用。是的,您将创建并启动一堆线程。但是在:buyers

System.out.println("Joining buyers. ");
for (Buyer buyer : buyers) {
    buyer.join();
    System.out.println("Joining thread: " + buyer.getName());
}

您没有在已创建并启动的线程(买家)上调用 join。并让您获得 NPE

buyer.join();

是因为你已经用 初始化了 Buyers 列表,认为你可以在循环中初始化:null

   for (Buyer buyer : buyers) {
        isPrime = (rand.nextInt(10) + 1 < 3);
        buyer = new Buyer(warehouse,
                          isPrime,
                          "buyer" + ++i);
        buyer.start();
        System.out.println("started buyer: " + i);
    }