Can someone please take a look at the code and help me out? I am failing the: The Person thread should run as long as isStopped is false condition, but my code is set up with the person method running while (! isStopped). It works for a similar condition for the Pharmacy thread, so I don't understand what is wrong. I have tried it both ways (!isStopped) and (isStopped). Writing the code the other way fails more conditions, so I think I am closer with while(!isStopped), but I can't figure out why it isn't working.
Thanks!
package com.codegym.task.task17.task1715;
import java.util.ArrayList;
import java.util.List;
/*
Pharmacy
*/
public class Solution {
public static DrugController drugController = new DrugController();
public static boolean isStopped = false;
public static void main(String[] args) throws InterruptedException {
Thread pharmacy = new Thread(new Pharmacy(), "Pharmacy");
Thread man = new Thread(new Person(), "Man");
Thread woman = new Thread(new Person(), "Woman");
pharmacy.start();
man.start();
woman.start();
Thread.sleep(1000);
isStopped = true;
}
public static class Pharmacy implements Runnable {
public void run(){
while (!isStopped){
drugController.buy(getRandomDrug(), getRandomCount());
for (int i = 0; i<3; i++){
waitAMoment();
}
}
}
}
public static class Person implements Runnable {
public void run(){
while (!isStopped){
drugController.sell(getRandomDrug(), getRandomCount());
for (int i =0; i<10; i++){
waitAMoment();
}
}
}
}
public static int getRandomCount() {
return (int) (Math.random() * 3) + 1;
}
public static Drug getRandomDrug() {
int index = (int) ((Math.random() * 1000) % (DrugController.allDrugs.size()));
List<Drug> drugs = new ArrayList<>(DrugController.allDrugs.keySet());
return drugs.get(index);
}
private static void waitAMoment() {
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
}