I'm trying to make List
of Effects
. Where class Effect
has duration after which this Effect
should be removed from List<Effect>
. This is my class Effect
:
public class Effect extends Thread {
private String title;
private Long duration;
@Override
public void run() {
try {
sleep(duration * 1000);
//todo remove this Effect from Effects object
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
and another class
with List<Effect>
called Effects
:
public class Effects extends Thread {
private List<Effect> effects = new ArrayList<>();
public void addEffect(Effect effect) {
effects.add(effect);
System.out.println(effects);
effect.start();
}
public void removeEffect(Effect effect) {
effects.remove(effect);
System.out.println(effects);
effect.stop();
}
}
I am trying to do it this way(again class Effect
):
public class Effect extends Thread {
private String title;
private Long duration;
private Effects effects;
public Effect(String title, Long duration, Effects effects) {
this.title = title;
this.duration = duration;
this.effects = effects;
}
@Override
public void run() {
try {
sleep(duration * 1000);
//todo remove this Effect from Effects object
effects.removeEffect(this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Main method:
public class Main {
public static void main(String[] args) {
Effects effects = new Effects();
Random random = new Random();
String msg;
do {
System.out.println("Press any key to add effect");
msg = new Scanner(System.in).nextLine();
if (!msg.equals("q")) {
effects.addEffect(new Effect("a", (long) random.nextInt(20), effects));
}
} while (!msg.equals("q"));
}
}
But to me it doesn't look like this is the right choice because both objects are nested inside each other. Is this normal or is there another way to do this?