关于java的线程问题(有可用答案就结贴)
初学者,不要见笑,不废话,三个类:
public class Operate //调用线程的主函数
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int bean = input.nextInt();
int machine = input.nextInt();
PrintBean pb = new PrintBean(machine);
Lock lock = new ReentrantLock();
for(int i=0;i<bean;i++){
new CreateArray(machine, lock).start();
}
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
pb.printBean();
}
}
public class CreateArray extends Thread //线程类
{
private int machine;
private Lock lock;
public CreateArray(){
}
public CreateArray(int machine,Lock lock)
{
this.machine = machine;
this.lock=lock;
}
public int createNumber(){
return (int)(Math.random()*2);
}
public int createMachine(){
int right=0;
for(int i=0;i<machine;i++){
int x = createNumber();
if(x==1){
right++;
}
}
return right;
}
public void run(){
lock.lock();
PrintBean pb = new PrintBean();
pb.operateArray(createMachine());
lock.unlock();
}
}
public class PrintBean //产生数组的类
{
int[] sorts;
public PrintBean(){
}
public PrintBean(int machine){
sorts = new int[machine];
}
public void operateArray(int x){
sorts[x-1]++; //跟了下到这里报nullpoint错
}
public void printBean(){
System.out.println(Arrays.toString(sorts));
}
}
先还奇怪为什么会报nullpoint错,后来debug发现到这里进了thread.class的方法
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}
很奇怪为什么会进这个方法,网上查了下资料很少,说什么无法捕获的错误,云里雾里,忘高手指点
------解决方案--------------------我还不如人呢,没人笑。
------解决方案--------------------int[] sorts;
你这东西初始化了吗
------解决方案--------------------Java code
public void run(){
lock.lock();
PrintBean pb = new PrintBean(); //构造方法用错了,sorts根本就没初始化
pb.operateArray(createMachine());
lock.unlock();
}
------解决方案--------------------
有点难度哦!
------解决方案--------------------
public void run(){
lock.lock();
PrintBean pb = new PrintBean();
pb.operateArray(createMachine());
lock.unlock();
}
}
你的这个方法中构造了一个PrintBean对象,调用的构造函数并没有给你的 int[] sorts;数组初始化,那么你调用 pb.operateArray(createMachine())的时候,数组没有初始化就对其进行sorts[x-1]++,当然会报nullpoint错误了啊,我说的楼主明白了么?