关于java的线程问题(有可用答案就结贴)
昆卡卡 2011-09-27 10:14:12 初学者,不要见笑,不废话,三个类:
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);
}
很奇怪为什么会进这个方法,网上查了下资料很少,说什么无法捕获的错误,云里雾里,忘高手指点