java - 如何在输出可接受时摆脱 java.lang.NullPointerException?

标签 java for-loop nullpointerexception

这对我来说解释起来有点复杂,所以请耐心等待。我正在模拟分配 PID 的进程标识符 (PID) 管理器。它已扩展为由一个多线程程序组成,该程序将分配 PID、随机 hibernate 一段时间,然后释放 PID。我有三个类(class);一个 PID 类、一个 Thread 类和一个驱动程序。我在驱动程序中有一个 PID 数组和一个线程数组。我已经设法将 PID 分配给数组中的每个 Thread 对象,但我总是在最后得到一个 java.lang.NullPointerException。这是代码:

    public class PID {

    private int pid;                    // Unique process identifier
    private boolean availability;       // Used to determine PID's availability--1 for available, 0 for unavailable

    public PID() {};                    // Empty constructor for PID object

    public PID(int p, boolean a) {      // Constructor for PID object with parameters
        pid = p;
        availability = a;
    };

    public void setPID(int pid) {                           // Sets PID's value
        this.pid = pid;
    }

    public void setAvailability(boolean availability) {     // Sets availability of PID
        this.availability = availability;
    }

    public int getPID() {                   // Gets array of PIDs
        return this.pid;
    }

    public boolean getAvailability() {
        return this.availability;
    }

    public void allocatePID(int pid) {      // Will allocate a PID and return PID
        this.setPID(pid);   
        this.setAvailability(false);
    }

    public void releasePID() {              // Will release PID to be available for use
        this.setAvailability(true);
    }
}

线程类

import java.util.*;

public class MyThread extends PID implements Runnable {

    public MyThread() {};   // Constructor for thread object                            

    public void run() {

    Random gen = new Random();                      // Generates random values
    int sleepTime;                                  // Sleep time
    sleepTime = gen.nextInt(60000 - 1000) + 1000;   // Generates random sleep time between 1 and 60 seconds (1000 ms and 60000 ms)

    try {   
        System.out.println("This thread will sleep for " + sleepTime + " seconds.");
        Thread.sleep(sleepTime);
    } catch (Exception e) {
            System.out.println(e);
        } 
        System.out.println("The thread has been terminated");
    }

}

和司机

 public class PID_Driver {

    public static void main (String[] args)
    {
        Random gen = new Random();          // Will generate a random numbers
        int randomInt;                      // Random integer values
        boolean randomBool;                 // Random boolean values

        final int NUM_OF_PIDS = 100;            // Constant number of PIDs
        final int NUM_OF_THREADS = 20;          // Constant number of threads

        int j = 0;

        PID[] pids = new PID[NUM_OF_PIDS ];         // Array of PID objects
        MyThread[] threads = new MyThread[NUM_OF_PIDS]; // Array of threads

        for (int i = 0; i < NUM_OF_PIDS ; i++) {                        
            pids[i] = new PID();                            // Creates a new PID object
            randomInt = gen.nextInt(5000 - 300) + 300;      // Generates a random integer value between 300 and 5000
            pids[i].setPID(randomInt);                      // Sets each PID value with random integer
            randomBool = gen.nextBoolean();                 // Generates a random boolean value
            pids[i].setAvailability(randomBool);            // Sets each availability status with a boolean value
        }

        for (int i = 0; i < NUM_OF_PIDS; i++) {
            System.out.printf("\n%-10s   ", "PID value ");
            System.out.printf("%8d", pids[i].getPID());
            System.out.printf("%8s", pids[i].getAvailability());
        }

        System.out.println();

        for (int i = 0; i < NUM_OF_THREADS; i++)
            threads[i] = new MyThread();                        // Creates new thread

        while (threads[NUM_OF_PIDS-1] == null) {
            for (int i = 0; i < NUM_OF_PIDS; i++) {
                    if ((pids[i].getAvailability())) {
                        threads[j].allocatePID(pids[i].getPID());
                        System.out.println("This thread has a PID value of " + threads[j].getPID() + " and its availability is now " + threads[j].getAvailability());
                        ++j;
                }
            }

        }
         // for (int i = 0; i < NUM_OF_THREADS; i++) {
            //threads[i].run();                             // Run the thread
//          threads[i].releasePID();                        // Release the thread

//      }

    }
    }

我知道这与我编写 for 循环以根据可用性将 PID 分配给线程的方式有关。我什至尝试在(疯狂的)尝试中添加一个 while 循环条件,以便在每个线程都被分配了一个 PID 后停止循环,但我没有成功。

编辑:这是堆栈跟踪:

Exception in thread "main" java.lang.NullPointerException
    at PID_Driver.main(PID_Driver.java:52)

所以基本上 NPE 出现在这一行:

threads[j].allocatePID(pids[i].getPID());

最佳答案

根据您的代码,您创建了一个包含 100 个线程的数组:

MyThread[] threads = new MyThread[NUM_OF_PIDS]; // Array of threads

但是,您只初始化前 20 个:

for (int i = 0; i < NUM_OF_THREADS; i++)
    threads[i] = new MyThread();                        // Creates new thread

然后,稍后调用此方法:

threads[j].allocatePID(pids[i].getPID());

除非你正在对 j 做一些我看不到的其他事情,否则它会保持在 0 <= j < 20 之内,当 j=20 时,它将尝试在未初始化的对象上调用该方法,从而导致异常。

关于java - 如何在输出可接受时摆脱 java.lang.NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17030936/

相关文章:

java - 如何解密 Whatsapp 数据库文件?

java - 在 PDF 文档中嵌入 OTF 字体

java - 建立非最终领域之前发生的最便宜方法

javascript - 类型错误 : Cannot read property '0' of undefined when comparing the arrays?

r - 在r中重命名列的循环

java - 显示两个字符串之间共享的字符

java - 为什么检索系统信息返回异常空点?

java - 哪种算法最适合我的列表管理?

java - 什么是NullPointerException,我该如何解决?

java - XML 解析 - 空对象引用 - Android