0

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.)

Lior Bar-On
  • 10,784
  • 5
  • 34
  • 46
pea_brain
  • 23
  • 4
  • You are much more likely to get help, if you provide us with the shortest possible piece of code that still shows the problem. In short, you should probably take some time to read and comprehend: https://stackoverflow.com/help/mcve – Micha Wiedenmann Jan 26 '19 at 18:29

2 Answers2

2

The problem is in you listInteger class.

public LinkedList<Integer> list;

gets never initialized, so you will have NullPointerException on every interaction with it. This will basically solve your problem.

public LinkedList<Integer> list = new LinkedList<>();

Also, the way you gonna use your list is broken. I would recommend you to read something about concurrency in java, about Java Memory Model and so on.

Also it would be really helpful for you to read something about naming conventions in java.

0

You never initialized your list inside your listInteger class Please change

public LinkedList<Integer> list;

to

public LinkedList<Integer> list=new LinkedList<>();
Ratish Bansal
  • 1,982
  • 1
  • 10
  • 19