The following code compiles but results in a null pointer exception at run time. My best guess is outputInts is not "visible" to each thread and therefore cannot be written to.
public class myClass{
ArrayList<int> outputints
public void foo(int start, int end) {
for (int i = start; i <= end; i++) {
bar(i);
}
private void bar(int i) {
class OneShotTask implements Runnable {
int i;
OneShotTask(int j) {
i = j;
}
@Override
public void run() {
try {
System.out.println(i);
outputints.add(i); //null pointer exception caused here
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
Thread t = new Thread(new OneShotTask(j));
t.start();
}
}
I've read that I should be using a callable to achieve this but I don't understand how this is implemented. Also the examples like java Runnable run() method returning a value seem to suggest that I can run a handful of threads using a callable where I may need somewhere in the region of a thousand threads.
I'm looking for help in getting either the above implementation to work or a layman's terms guide to how it can be achieved with a callable