package com.codegym.task.task17.task1715;
import java.util.ArrayList;
import java.util.List;
/*
Pharmacy
Requirements:
6. The Pharmacy thread must use drugController to purchase a random drug (getRandomDrug)
in a random amount (getRandomCount).
7. The Pharmacy thread should use the waitAMoment() method to wait 300 ms between purchases.
8. The Person class must implement the Runnable interface.
9. The Person thread should run as long as isStopped is false.
10. The Pharmacy thread must use drugController to sell a random drug (getRandomDrug) in
a random amount (getRandomCount).
11. The Person thread should use the waitAMoment() method to wait 100 ms between purchases.
12. The methods of the DrugController class must be synchronized.
*/
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());
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());
waitAMoment();
}
}
}
public static class Person implements Runnable{
public void run(){
while(!isStopped){
drugController.sell(getRandomDrug(),getRandomCount());
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() {
for(int i = 0; i < 3; i++)
waitAMoment();
}
}
help me pls
Archived
Comments (1)
- Popular
- New
- Old
You must be signed in to leave a comment
Ivaylo Trifonov
9 August 2019, 15:25
Well, the first requirement that You don't meet says that You have to wait (use sleep()) for 300ms and in the same tame use the waitAMoment() method who waits only 100ms. You don't have to change the method otherwise will cause an error. In this case, consider the use of some loop only when it is needed (but not inside the waitAMinute method code block). Changing the code will clear the other two errors in Your revision because Your change makes the two run() methods to run for longer then required. Leave the waitAMinute() like it was and implement the loop where is it required more wait (sleep()) time.
0