I am working on a quite complicated code that I want to include threads in. For a better understanding, I was playing around with threads a little and got a NullPointerException
that I don't know why it is there:
Here is my main method and the two classes that are used:
public static void main (String args[]) {
listInteger list = new listInteger();
for(int i = 0; i < 10; i++) {
list.add(i);
}
printList printy = new printList(list);
Thread no1 = new Thread(printy);
Thread no2 = new Thread(printy);
no1.start();
no2.start();
}
public class printList implements Runnable {
public listInteger list;
public printList(listInteger list) {
this.list = list;
}
@Override
public void run() {
while(list.size() > 0) {
System.out.println(list.getFirst());
list.removeFirst();
}
}
}
public class listInteger {
public LinkedList<Integer> list;
public Integer getFirst() {
return list.getFirst();
}
public void removeFirst() {
list.removeFirst();
}
public int size() {
return list.size();
}
public void add(Integer e) {
list.add(e);
}
}
I thought it would just print out the numbers. I wanted to see when the thread gets terminated and also play around with synchronized to see the difference of the output. The list was supposed to show me what the threads are doing but I didn't even get to that point. When does it point to null? Am I doing something wrong with .add()? (I am working on my actual code for many hours now. Forgive me if it is obvious, I just don't see it.)