I have created a Fish class that simulates a fish that reproduces in a Java program. Each fish must breed by meeting another random fish. But the problem is that two fish find each other as a pair and create two children at the same time. This process of reproduction is repeated several times at the same time.
I am keeping fish in Aquarium class. After the fish is born, after it reaches the breeding age (ie should start at 4 years old), it should find a random mate from the Aquarium class. But in the code I wrote, a fish wants to find a mate and reproduce, and at this moment, that fish also reproduces by choosing the first fish from the Aquarium class. Two fishes will be born in one place in the sea. Actually, one fish should be born. I can’t figure out how to solve this problem. The real problem is in the method of reproduction. Where and how to write it. Please suggest me optimal solutions. Thanks in advance for the replies everyone.
I have a Fish class:
package lesson.uz;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.util.Random;
@Getter
@Setter
@EqualsAndHashCode
public class Fish extends Thread {
private long id;
private Gender gender;
private Integer lifespan;
private String fishName;
private Integer age = 0;
private static Long counter = 1L;
public Fish(Gender gender) {
this.gender = gender;
this.lifespan = new Random().nextInt(11)+40;
this.fishName = "Fish"+ counter++;
this.id = Math.abs(new Random().nextLong() * System.currentTimeMillis());
System.out.println(fishName + " created. "+System.currentTimeMillis());
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
reproduce();
age++;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public void reproduce() {
Fish randomFish = getRandomFish();
long count = Aquarium.raddom.stream().filter(id -> randomFish.getId() == id || this.getId() == id).count();
if (count == 0 && this.age >= 4 && randomFish.getAge() >= 4 && this.getGender() != randomFish.getGender()) {
Aquarium.raddom.add(this.id);
Aquarium.raddom.add(randomFish.id);
System.out.println(this.fishName + " and " + randomFish.getFishName() + " meet.n");
Fish babyFish = createFish();
Aquarium.fishList.add(babyFish);
Aquarium.raddom.remove(this.id);
Aquarium.raddom.remove(randomFish.id);
}
}
public static Fish createFish() {
Fish newFish = new Fish(Math.random() > 0.5 ? Gender.MALE : Gender.FEMALE);
newFish.start();
return newFish;
}
public Fish getRandomFish() {
int randomNum = 0;
Fish currenFish = null;
while (true) {
randomNum = new Random().nextInt(Aquarium.fishList.size());
currenFish = Aquarium.fishList.get(randomNum);
if (this != currenFish) {
break;
}
}
return currenFish;
}
}
I have a Aquarium class:
package lesson.uz;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Aquarium extends Thread {
public static List<Fish> fishList = new ArrayList<>();
public static List<Long> raddom = new ArrayList<>();
@Override
public void run() {
}
}
and Main class:
package lesson.uz;
public class Main {
public static void main(String[] args) {
Aquarium aquarium = new Aquarium();
aquarium.start();
init();
}
public static void init() {
Fish fish1 = new Fish(Gender.MALE);
fish1.start();
Aquarium.fishList.add(fish1);
Fish fish2 = new Fish(Gender.FEMALE);
fish2.start();
Aquarium.fishList.add(fish2);
}
}
Problem (Problem):
Fish A and Fish B choose each other as a mate.
At the same time, Fish B also selects Fish A and begins the process of reproduction in parallel.
As a result, two children are created at the same time.
Question:
How to solve this problem? How can you ensure that the reproduction process only happens once at a time?
public static List<Long> raddom = new ArrayList<>();
I tried to solve the problem by adding a raddom(in the sense of a maternity ward) list. My program is not finished yet. But it didn’t help. Please suggest me optimal solutions.
Tuychi Sharipov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
High Level
I would remove the reproduce method from the Fish class and place it in the Aquarium class. When a fish is old enough to reproduce it will call the Aquarium reproduce method. The Aquarium will add the Fish to the list, if there are at least two fish in the list, remove them, and create a new fish. (There may be a better way to implement this, but it will work.)
I also recommend changing new ArrayList<>();
to Collections.synchronizedList(new ArrayList<>())
.
If this is a real problem and not just a training exercise, you can’t have one fish per thread… Number of fishes grows exponentially and you will run out of threads fast.
Usually people have single threaded games (this looks like a little game to me):
public class Fish {
int age;
@Getter
GENDER gender;
boolean pregnant;
enum GENDER {
MALE,
FEMALE
}
public boolean isLookingForPartner() {
return !isDead() && age >= 2 && !pregnant;
}
public void getPregnant() {
if (gender == GENDER.FEMALE) {
pregnant = true;
}
}
public Fish giveBirth() {
if (pregnant) {
pregnant = false;
//generate random gender
GENDER randomGender = Math.random() < 0.5 ? GENDER.MALE : GENDER.FEMALE;
System.out.println("NEW BABY FISH");
return new Fish(0, randomGender, false);
}
return null;
}
public boolean isDead() {
return age >= 10;
}
public void tick() {
age++;
}
}
public class Container {
private final List<Fish> fishList;
public Container(List<Fish> fishList) {
this.fishList = fishList;
}
public void addFish(Fish fish) {
fishList.add(fish);
}
public void tick() {
fishList.removeIf(Fish::isDead);
List<Fish> babies = new ArrayList<>();
for (Fish fish : fishList) {
fish.tick();
Fish baby = fish.giveBirth();
if (baby != null) {
babies.add(baby);
}
}
fishList.addAll(babies);
List<Fish> maleFish = fishList.stream().filter(it -> it.getGender() == Fish.GENDER.MALE).collect(Collectors.toList());
List<Fish> femaleFish = fishList.stream().filter(it -> it.getGender() == Fish.GENDER.FEMALE).collect(Collectors.toList());
int femaleCounter = 0;
for (Fish male : maleFish) {
if (!male.isLookingForPartner()) {
continue;
}
Fish female = null;
while (female == null || !female.isLookingForPartner()) {
if (femaleCounter == femaleFish.size()) {
return;
}
female = femaleFish.get(femaleCounter);
femaleCounter++;
}
female.getPregnant();
}
}
public static void main(String[] args) throws InterruptedException {
Container container = new Container(new ArrayList<>());
container.addFish(new Fish(0, Fish.GENDER.FEMALE, false));
container.addFish(new Fish(0, Fish.GENDER.MALE, false));
int iteration = 0;
while (true) {
container.tick();
Thread.sleep(300);
iteration++;
System.out.printf("Iteration {}", iteration);
}
}
}
2