java - 实例化所有成员后枚举数组时出现 NullPointerException?
问题描述
我正在处理一段涉及线程的代码,并且我已经设置了以下 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;
}
}
解决方案
问题在于:
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();
是因为你已经用 初始化了买家列表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);
}
推荐阅读
- shell - 抑制 Ansible 警告(至少对于 aptitude install)
- python - X轴标签未显示在图中python
- jenkins - Jenkins 声明式管道:如何在不存档的情况下对文件进行指纹识别?
- c# - 有没有办法在 asp.net 中以编程方式检索偏好颜色方案(暗/亮模式)
- python - 为什么 * 在赋值语句和函数调用中的工作方式不同?
- node.js - 我的 node.js 驱动的应用程序只能从一些远程客户端访问,而不能从其他客户端访问。如何让所有客户访问它?
- javascript - 如何从TestCafe中的window对象获取构造函数?
- java - 如何使用递归来简化重复代码?
- javascript - AmCharts 4 Force Directed Chart - 按父级选择气泡 -> 子级位置
- java - 在 Spock 中,如何测试从另一个静态方法调用的静态方法?