关于java的线程问题(有可用答案就结贴)

昆卡卡 昆卡卡 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
初学者,不要见笑,不废话,三个类:
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);
}
很奇怪为什么会进这个方法,网上查了下资料很少,说什么无法捕获的错误,云里雾里,忘高手指点
...全文

相关推荐

评论 29
收藏 已收藏
分享
返回顶部
昆卡卡
Java SE 62,620 成员 307,251 内容