我完全从我的并行编程书中复制了这段代码。当我尝试编译它时,我会在代码中发生nullpointerexception: t [i] = newThread(counters [i]); 根据Eclipse是一个过时的方法。
我做的唯一修改是添加一个try {} catch {}来捕获nullpointerexceptions以允许程序实际运行。
有没有人确切知道出了什么问题/如何修复它。 提前致谢
CODE
import java.util.*;
import java.util.concurrent.*;
public class CountThrees implements Runnable
{
private static final int ARRAY_LENGTH=100000;
private static final int MAX_THREADS=10;
private static final int MAX_RANGE=100;
private static final Random random=new Random();
private static int count=0;
private static Object lock=new Object();
private static int[] array;
private static Thread[] t;
public static void main(String[] args)
{
array=new int[ARRAY_LENGTH];
//initialize elements in the array
for(int i=0;i<array.length;i++)
{
array[i]=random.nextInt(MAX_RANGE);
}
//create the threads
CountThrees[] counters=new CountThrees[MAX_THREADS];
int lengthPerThread=ARRAY_LENGTH/MAX_THREADS;
for(int i=0; i<counters.length; i++)
{
counters[i]=new CountThrees(i*lengthPerThread,lengthPerThread);
}
//run the threads
for(int i=0;i<counters.length; i++)
{
try
{
t[i]=new Thread(counters[i]); //NullPointerException Happens here
t[i].start();
}
catch(NullPointerException d)
{
System.out.println("Null Pointer Exception Happened");
}
}
for(int i=0;i<counters.length;i++)
{
try
{
t[i].join();
}
catch(InterruptedException e)
{}
catch(NullPointerException f)
{
System.out.println("Null Pointer Exception Happened");
}
}
//print the number of threes
System.out.println("Number of threes: " + count);
}
private int startIndex;
private int elements;
private int myCount=0;
public CountThrees(int start,int elem)
{
startIndex=start;
elements=elem;
}
//Overload of run method in the Thread class
public void run()
{
for(int i=0;i<elements; i++)
{
if(array[startIndex+i]==3)
{
myCount++;
}
}
synchronized(lock)
{
count+=myCount;
}
}
}
答案 0 :(得分:2)
你永远不会分配数组t。你得到的空指针异常是因为你的t数组是null。您需要在main方法的开头添加此权限:
t = new Thread[MAX_THREADS];
答案 1 :(得分:0)
我浏览了它,但我认为问题是你在尝试将数据分配给t之前没有为t分配内存。 Java中的数组是指针。你要做的是在C:
中这样做static thread* t;
//Need to initialize t here using t = new t[MAX_THREADS]
t[i] = ...
将抛出NullPointerException。