请问是怎么做到在不对方法添加参数的情况下 让 waitAMoment() 方法 既可以等待100毫秒又可以等待300毫秒的?
我的想法是这样的,但是并不可以这样做
private static void waitAMoment(Object o) {
try {
if(o instanceof Pharmacy)
Thread.sleep(300);
else
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
package zh.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(), "男士");
Thread woman = new Thread(new Person(), "女士");
pharmacy.start();
man.start();
woman.start();
Thread.sleep(1000);
isStopped = true;
}
public static class Pharmacy implements Runnable{
@Override
public void run() {
while (!isStopped){
drugController.buy(getRandomDrug(),getRandomCount());
waitAMoment();
}
}
private static void waitAMoment() {
try {
Thread.sleep(300);
} catch (InterruptedException ignored) {
}
}
}
public static class Person implements Runnable{
@Override
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() {
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
}