【问题标题】:creating multiple thread objects in a loop [duplicate]在循环中创建多个线程对象[重复]
【发布时间】:2016-04-28 15:11:11
【问题描述】:

我怎样才能摆脱这个问题。如何创建多个线程对象?

public void filterControl (int threadCount) {
    this.rowCount = img.getHeight() / threadCount;
    Thread[] t = null;

    for (int i=0; i<threadCount; i++) {
        t[i] = new Thread(new Runnable(){ //there is a NullPointerException

            @Override
            public void run() {
                filtering(startRow, rowCount);
            }
        });

        t[i].run();
    }
}

【问题讨论】:

    标签: java arrays multithreading nullpointerexception thread-safety


    【解决方案1】:

    您的NullPointerException 来自于您将数组初始化为null

    将其初始化为:

    Thread[] t = new Thread[threadCount];
    

    这会将其所有元素初始化为nullObjects 的默认值),但数组本身为非null 实例,共有threadCount 元素槽。

    注意

    您不会通过调用run 来启动Thread,这将在调用线程中执行run 方法。

    请改用t[i].start();

    【讨论】:

    • 请解释一下否决票?
    【解决方案2】:

    在尝试使用“数组”之前创建一个数组。

    尝试替换

    Thread[] t = null;
    

    Thread[] t = new Thread[threadCount];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 2018-11-05
      相关资源
      最近更新 更多