Reputation: 11
I have a problem in java programming , how can i make all objects of a class invoke a method of themselves simultaneously in java ?
thank in advance.
Upvotes: 0
Views: 129
Reputation: 15758
Here is an example code for what I understood of your question:
public class Flip {
private static List<Flip> instances = new ArrayList<Flip>();
[... fields, etc]
public Flip() {
[...init the fields]
synchronized(instances) {
// if you access the instances list, you have to protect it
instances.add(this); // save this instance to the list
}
}
[... methods]
public void calculate() {
synchronized(instances) {
// if you access the instances list, you have to protect it
for (Flip flip : instances) {
// call the doCalculate() for each Flip instance
flip.doCalculate();
}
}
}
private void doCalculate() {
[... here comes the original calculation logic]
}
}
The key point is that you have to register all instances of Flip somehow. Later on you can iterate them through.
Upvotes: 0
Reputation: 4675
From what I understand of your question, why don't you keep all instances of the class in a collection and then iterate over them and invoke the method you wish on all of them?
Upvotes: 1