Reputation: 487
Please help me with my code. I'm making a race using There are 2 points in the Race starting point and the finish line. All horses started at the gate and proceed to the gate. The race will only starts once all horses reached the gate. The one who finished first wins the race.
Upvotes: 1
Views: 283
Reputation: 2673
The mistake you have is the number you provide here
gate= new CyclicBarrier(numHorses);
What is numHorses ?
It's the number of all horses but here :
list.removeIf(...);
You are removing the horses under 18, pretend we had 5 horses total, numHorses==5
is true, two of these are under 18 so we're left with 3.
You're creating three threads but the barrier is set on 5, the barrier will never get passed because it's waiting for 5 threads when there are only three.
The solution is to make addHorsesToList
add horses without the barrier(so you'll need a Horse
constructor without barrier too), then you move gate = new CyclicBarrier
to after the list.removeIf
and change numHorses
to list.size()
.
After that you assign the barrier to the gate
field of every horse object you have in list
.
Do like this :
int canJoin=0;
while(canJoin<2){
list= new ArrayList<Horse>();
numHorses=checkNumHorses();
addHorsesToList();
printHorses();
canJoin=countJoinAge();
}
list.removeIf(p -> p.Age().equals(18));
int numHealthyHorses=list.size();
gate=new CyclicBarrier(numHealthyHorses);
System.out.println("Horses who can join");
Thread[] threads = new Thread[numHealthyHorses];
for(Horse horse: list){ //create thread for each Horse
horse.setGateBarrier(gate); //setter method, needs to be added to Horse class
threads[numThread]= new Thread(horse);
}
for(int i=0;i<numHealthyHorses;i++){ //start the thread for each horse
threads[i].start();
}}
Upvotes: 1