简体   繁体   English

在多个线程上使用Thread.join的NullPointer异常

[英]NullPointer Exception using Thread.join on multiple threads

I have the following issue with one of my Java programs. 我的一个Java程序出现以下问题。 I'm trying to launch several threads depending on what my main program find on the file system. 我正在尝试启动多个线程,具体取决于我的主程序在文件系统上找到的内容。 The way it works is quite classic: - First loop: instantiate, store in a local array and start a new thread - Second loop: wait all of thread with '.join()' method 它的工作方式非常经典:-第一个循环:实例化,存储在本地数组中并启动新线程-第二个循环:使用'.join()'方法等待所有线程

At execution i get a NullPointerException on the '.join()'. 执行时,我在'.join()'上得到了一个N​​ullPointerException。 This exception is thrown by the 3rd thread launched (because it finishes before the 2 first one) 此异常由启动的第三个线程引发(因为它在第2个线程之前完成)

This is an example of my code: 这是我的代码的示例:

PackageManager[] myRootManagers = new PackageManager[myCCDirs.size()];
int i = 0;
for (PkgDescriptor descriptor : myCCDirs) {
    ...
    // --- instantiate new ROOT manager
    myRootManagers[i] = new PackageManager(getConfig(), loggerPac, descriptor);
    // --- start it
    myRootManagers[i].start();
}

for (PackageManager packageManager : myRootManagers) {
    try {
        packageManager.join();
    }
    catch (InterruptedException e) {
        loggerPac.error("...");
    }
}

Does someone know why this exception occurs ? 有人知道为什么会发生这种异常吗?

Make sure all i in the first loop covers all valid indecies in the myRootManagers array. 确保第一个循环中的所有i都覆盖myRootManagers数组中的所有有效指标。

Note that you should increment i in the end of the first for loop, since array indecies are 0-based.: 请注意,您应该在第一个for循环的末尾增加i ,因为数组索引基于0。

int i = 0;
for (PkgDescriptor descriptor : myCCDirs) {
    ...
    // --- instantiate new ROOT manager
    myRootManagers[i] = new PackageManager(getConfig(), loggerPac, descriptor);
    // --- start it
    myRootManagers[i].start();

    i++;   // <-----------------------------------
}

As a debugging step, I would add 作为调试步骤,我将添加

System.out.println(Arrays.toString(myRootManagers));

after the first loop, to assert that there are no null references left. 在第一个循环之后,断言没有null引用。

This seems odd to me unless you hidden the important part: 除非您隐藏了重要部分,否则这对我来说似乎很奇怪:

for (PkgDescriptor descriptor : myCCDirs) {
    ...
    // --- instantiate new ROOT manager
    myRootManagers[i] = new PackageManager(getConfig(), loggerPac, descriptor);
    // --- start it
    myRootManagers[i].start();
}

You iterate over myCCDirs but initialize myRootManagers objects, maybe you didn't increment i ? 您遍历myCCDirs但初始化了myRootManagers对象,也许您没有增加i

This could also happen if a myCCDirs is removed in another thread. 如果在另一个线程中删除了myCCDirs,也会发生这种情况。

PackageManager[] myRootManagers = new PackageManager[myCCDirs.size()]; // size is 3
int i = 0;
for (PkgDescriptor descriptor : myCCDirs) { // size is now 2 so the last field is not set.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM