Java Nullpointerexception and obsolete method
I copied this code exactly out of my parallel programming book. When I tried compiling it I go a nullpointerexception which seems to be happening at the code: t[i]=newThread(counters[i]); which according to the Eclipse is an obsolete method.
The only modification I made was adding a try{}catch{} to catch nullpointerexceptions to allow the program to actually run.
Does anyone know exactly what is going wrong/how to fix it. Thanks in advance
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 开发者_如何学GoException 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;
}
}
}
You never allocate the array t. The null pointer exception you're getting is because your t array is null. You need to add this right at the beginning of your main method:
t = new Thread[MAX_THREADS];
I skimmed it but I think the problem is that you are not allocating memory for t before trying to assign data to t. Arrays in Java are pointers. What you are trying to do is like this in C:
static thread* t;
//Need to initialize t here using t = new t[MAX_THREADS]
t[i] = ...
Which will throw a NullPointerException.
精彩评论