Мне было поручено выполнить одну задачу, и я старался изо всех сил, но не смог ее выполнить. Задача состоит в том, чтобы написать Java-программу, которая будет готовить блины, и в то же время случайным образом будут выбираться пользователи, которые будут есть приготовленные блины. Эти две вещи должны выполняться одновременно, а это означает, что во время приготовления блина пользователи будут проверять, есть ли готовый блин, а затем съедать его. Ожидается, что каждый пользователь съест максимум 5 блинов, а производитель блинов должен приготовить максимум 12 блинов за заданное время. Все это должно произойти всего за 20 секунд, а затем программу следует завершить и распечатать отчет через 20 секунд. Инструкция также заключалась в том, что я должен заставить эти две вещи работать одновременно, но не использовать Thread или ExecutorService. Мне действительно нужна помощь, как этого достичь. Вот что я попробовал, и у меня получается бесконечный цикл метода ProducePancake, он даже не позволяет выполнить метод eatPancake.
public class PanCakeTask {
int consumedPancake = 0;
int availablePancake = 0;
int totalPancakeProduced = 0;
List usersList = new ArrayList();
void producePancake(HashMapusers){
// first check the total pancake produced so far by checking the number
// of pancakes eaten by the users plus the available ones
for (String user: users.keySet()){
consumedPancake +=users.get(user);
}
totalPancakeProduced += consumedPancake + availablePancake;
while (totalPancakeProduced =1){
//user will now eat the pancake
//then increment the number of pancake eaten by that user
// and decrement the number of pancakes available
int newCount = numberEaten + 1;
availablePancake -=1;
//finally update the user that just eaten the pancake
users.put(usersList.get(0),newCount);
System.out.println("Eaten a pancake");
}
}
}
public void performTask(){
//Hashmap is used to store the users because of key-value pairs
HashMap users = new HashMap();
users.put("user1",0);
users.put("user2",0);
users.put("user3",0);
usersList.addAll(users.keySet());
System.out.println(users);
System.out.println(usersList);
//This task can only be executed in 20 seconds
long startTimeInSeconds = System.currentTimeMillis()/1000;
long requiredTime = startTimeInSeconds +20;
while (startTimeInSeconds !=requiredTime){
//only continue the process if it has not exceeded 20 seconds
System.out.println("Start time is "+startTimeInSeconds);
System.out.println("End time is "+requiredTime);
//This two method is to be executed concurrently without using Thread or ExecutorService
// I need help on how to achieve that without the use of Thread or ExecutorService
producePancake(users);
eatPancake(users);
startTimeInSeconds = System.currentTimeMillis()/1000;
}
System.out.println("Total number of cake produced is "+totalPancakeProduced);
System.out.println("Total number of cake eaten is "+consumedPancake);
System.out.println("Total number of pancake remained is "+availablePancake);
System.out.println("Time start is "+startTimeInSeconds);
System.out.println("Time completed is "+requiredTime);
}
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... torservice