开发者社区> 问答> 正文

线程中传递数组时抛出空指针异常问题

在写一个排序算法演示程序;先在主窗体中的Listener中调用engine:

private class StartListener implements ActionListener{
        public void actionPerformed(ActionEvent e){

            
            int[] unsort=UnsortGenerator();  //函数返回给unsort一个数组
            
            
            engine.setArray(unsort);
            engine.setAlgorithm(getAlgorithm());
            engine.setSleepTime(jslSpeed.getValue()*50);
            engine.setHistogram(histogram);  //Histogram是用来画柱状图的
            engine.run();
        }
    }

然后在Engine中:

private SelectionSort selectionSort=new SelectionSort();
...
if (thread != null && thread.getState() != Thread.State.TERMINATED)
                return;
            
            thread=new Thread(selectionSort);
            selectionSort.setArray(unsort);
            thread.start();

在SelectionSort中:

public class SelectionSort implements Runnable{
    private int[] unsort;
    private Histogram histogram;
    private int sleepTime;
    
    public void run(){
        selectionSort();
    }

    public void setArray(int[] unsort){
        this.unsort=unsort;
    }
    
    private void selectionSort(){
        
        int key=0;
        int count=0;
        while(count<unsort.length-1){
            for(int i=key+1;i<unsort.length;i++){
                if(unsort[key]>unsort[i])
                    key=i;
            }    
            int temp=unsort[count];
            unsort[count]=unsort[key];
            unsort[key]=temp;
            
            count++;
            key=count;
            
            for(int i=0;i<unsort.length;i++)
                System.out.printf("%d ",unsort[i]);
            System.out.print('\n');//这里可以输出正常数组

            histogram.showHistogram(unsort);//这里会抛出异常

            try {
                Thread.sleep(sleepTime);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

1
请问这段代码哪里有问题?如何修改?

展开
收起
蛮大人123 2016-03-05 11:30:52 2478 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    空指针异常在于histogram而不在于unsort。engine中只设置了array,再设置上histogram就可以了

    2019-07-17 18:53:07
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
多IO线程优化版 立即下载
建立联系方法之一 立即下载
低代码开发师(初级)实战教程 立即下载