Reputation: 1
I'm currently working on a java project and something is embarassing me : I'm using threads, so I have a thread called "chicken", with a method called "direction()", in which I give a X and a Y where it has to go.
I then use this method in the run() method of the thread.
this.direction(NX,NY);
I also have a main class called "test1", in which I start the chickens, & I also have a "food" class:
Chicken C1=new Chicken(50,750,1,true);
Chicken C2=new Chicken(750,750,2,true);
Chicken C3=new Chicken(200,50,3,true);
C1.start();
C2.start();
C3.start();
Food F1=new food(x,y);
The position of the food is chosen by the player with his mouse.
The problem is, the values x and y are often changing as Chicken have to go toward the food, and the position can only be found in the food class/in the test1 For now, I made a global variable in Test1 that I can change whenever I want and that I use in the thread chicken, like :
NX=Test1.x;
NY=Test1.y;
I don't like using global variable, is there another way of doing this?
Upvotes: 0
Views: 263
Reputation: 140524
Instead of using a global variable, inject the instance of Food
into each of your Chicken
s' at construction time:
Food food = new Food(x, y);
Chicken C1=new Chicken(50,750,1,true,food);
Chicken C2=new Chicken(750,750,2,true,food);
Chicken C3=new Chicken(200,50,3,true,food);
and store it in a member variable on Chicken. Then you can use e.g. this.direction(food.x, food.y)
(although you would need some means of ensuring that updates to x and y are visible to all threads, e.g. making them volatile, or providing synchronized getters).
Upvotes: 3
Reputation: 816
Instead of using a global variable you should implement the food class as a singleton design pattern (https://en.wikipedia.org/wiki/Singleton_pattern) This design pattern ensures that your object is only instantiated once and you can retrieve that unique instance with a static class method (usually called getInstance). The constructor should be private to prevent you for instantiating to guarantee a unique instance.
Example where the object is instantiated on the first call to get instance (lazy):
public class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Since you are using threads I would recommend using the keyword synchronized
on the setters changing the position of the food to avoid having multiple threads modifying the value at the same time (if you intend to modify it in multiple threads).
Upvotes: 0