Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当输出可以接受时,如何消除java.lang.NullPointerException?_Java_For Loop_Nullpointerexception - Fatal编程技术网

当输出可以接受时,如何消除java.lang.NullPointerException?

当输出可以接受时,如何消除java.lang.NullPointerException?,java,for-loop,nullpointerexception,Java,For Loop,Nullpointerexception,这对我来说有点复杂,所以请耐心听我解释。我正在模拟一个分配PID的过程标识符(PID)管理器。它被扩展为包含一个多线程程序,该程序将分配PID,在一段随机时间内休眠,然后释放PID。我有三节课;一个PID类、一个线程类和一个驱动程序。我在驱动程序中有一个PID数组和一个线程数组。我已经设法将PID分配给数组中的每个线程对象,但最后总是得到一个java.lang.NullPointerException。代码如下: public class PID { private int p

这对我来说有点复杂,所以请耐心听我解释。我正在模拟一个分配PID的过程标识符(PID)管理器。它被扩展为包含一个多线程程序,该程序将分配PID,在一段随机时间内休眠,然后释放PID。我有三节课;一个PID类、一个线程类和一个驱动程序。我在驱动程序中有一个PID数组和一个线程数组。我已经设法将PID分配给数组中的每个线程对象,但最后总是得到一个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

//      }

    }
    }
因此,基本上NPE出现在这一行:

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

Victor是对的,当
j
达到20时,它总是会抛出一个NPE。如果您想在while循环中转到
threads[NUM\u OF_PIDS-1]
,那么您必须使用新的
MyThread
对象通过
threads[99]
填充
threads[20]

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

while (threads[NUM_OF_THREADS-1].getPID() == 0) {
    ...
}
我猜这是一个复制错误。这条线

MyThread[] threads = new MyThread[NUM_OF_PIDS]; // Array of threads
应该是

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

根据您的代码,创建一个包含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

除非你对j做了我看不到的其他事情,使其保持在0以内,否则我们可以得到堆栈跟踪吗?@DavidChristo如果我可以问的话,为什么在这种情况下需要堆栈跟踪?当发生异常时,如果你知道程序死掉的确切位置,那么追踪原因就容易多了。NPE的原因之一是
NUM\u of theu PIDS>NUM\u of theu THREADS
THREADS[]
的尾部设置为
null
,因为你只初始化了
NUM\u of theu THREADS
元素,这会在
线程[j]触发NPE。allocateId(…)
@DavidChristo:啊,好的。我不知道堆栈跟踪是什么,但我明白你的意思。我现在就把它包括进去。这很有道理。非常感谢你。
for (int i = 0; i < NUM_OF_THREADS; i++)
    threads[i] = new MyThread();                        // Creates new thread
threads[j].allocatePID(pids[i].getPID());