多线程 - Java一个线程中传递数组时抛出空指针异常
ringa_lee
ringa_lee 2017-04-17 10:57:11
[Java讨论组]

在写一个排序算法演示程序

先在主窗体中的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();
			}
		}
	}
}

请问这段代码哪里有问题?如何修改?
提前感谢!

ringa_lee
ringa_lee

ringa_lee

全部回复(1)
PHP中文网

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号