如果输出可以接受,如何摆脱java.lang.NullPointerException?

时间:2013-06-10 19:01:55

标签: java for-loop nullpointerexception

这对我来说有点复杂,所以请耐心等待。我正在模拟分配PID的进程标识符(PID)管理器。它已被扩展为由多线程程序组成,该程序将分配PID,随机休眠一段时间,然后释放PID。我有三节课; PID类,Thread类和驱动程序。我在驱动程序中有一个PID数组和一个Thread数组。我已经设法将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);
    }
}

Thread类

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());

2 个答案:

答案 0 :(得分:4)

根据您的代码,您创建一个包含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&lt; = j&lt; 20,当j = 20时,它会尝试在未初始化的对象上调用该方法,从而导致异常。

答案 1 :(得分:1)

Victor是对的,当j达到20时,它总是会抛出NPE。如果你想在你的while循环中转到threads[NUM_OF_PIDS-1],那么你将不得不填充{{1通过threads[20]使用新的threads[99]个对象。

否则,如果您只想确保所有线程都获得PID,那么将while循环条件更改为:

MyThread

我猜这是一个复制面食错误。这一行

while (threads[NUM_OF_THREADS-1].getPID() == 0) {
    ...
}

应该是

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