user3470812
user3470812

Reputation: 13

Threads and ArrayList in Java

I have a class Food which creates foods and starts a new thread. Amongst other things.

private Thread foodThread;
public void start() {
    foodThread = new Thread(this, "Food");       
    foodThread.start();
}

The I have a board class which has an Arraylist buffet which uses the methods from Food.

ArrayList<Food> buffet;
for (int i=0; i<15; i++){
        buffet.add(new Food(this));

    }

Now what I want to do is start a new thread from the Food class so (foodThread) inside the for loop. I tried

public Food food; 

and then

food.start();

inside the loop but that doesn't seem to work, it just throws an error.java.lang.NullPointerException

Upvotes: 0

Views: 78

Answers (2)

Fildor
Fildor

Reputation: 16104

If you have this in your code :

public Food food; // <- Here you only declare a variable "food" of Type "Food" 
                  //    No object (of Type Food) instance has been created, yet!
food.start();     // <- Will throw NPE

Like this, then you have to also instantiate a Food object!

Like ...

public Food food = new Food(); 
food.start();

Another possible source of the NPE is in @subash 's answer ...

Just a hint for future questions: In the stacktrace ( the error messages that are displayed, where you saw the NullPointerException) there should be even line numbers and packages/classes mentioned. So you should especially in the case of NPE be able to track down where you forgot to instantiate an object.

UPDATE

If you changed

for (int i=0; i<15; i++){
    buffet.add(new Food(this));
}

to this:

for (int i=0; i<15; i++){
    Food localFood = new Food(this); // Create instance, variable is only valid and visible inside this block.
    buffet.add(localFood);           // Add the instance to your buffet.
    localFood.start();               // Start the instance's thread.
}                                    // Next, please.

it should do what you intended.

Sidenote: you should code against Interfaces. That means you better do something like

List<Food> buffet = new ArrayList<Food>();
// ^-Interface "List"    ^- Concrete implementation of the interface. Easily exchangeable for other implementation later on.

Upvotes: 2

subash
subash

Reputation: 3140

initialize the ArrayList

ArrayList<Food> buffet = new ArrayList<Food>();

Upvotes: 1

Related Questions