Advertisement
jaVer404

level17.lesson10.home03

Sep 28th, 2015
378
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.73 KB | None | 0 0
  1. package com.javarush.test.level17.lesson10.home03;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. /* Аптека
  7. Реализуй интерфейс Runnable в классах Apteka и Person.
  8. Все нити должны работать пока не isStopped
  9.  
  10. Логика для Apteka: drugsController должен сделать закупку случайного лекарства (getRandomDrug)
  11. в количестве (getRandomCount) и подождать 300 мс
  12.  
  13. Логика для Person: drugsController должен сделать продажу случайного лекарства (getRandomDrug)
  14. в количестве (getRandomCount) и подождать 100 мс
  15.  
  16. Расставь synchronized там, где это необходимо
  17. */
  18.  
  19. public class Solution {
  20.     public static DrugsController drugsController = new DrugsController();
  21.     public static boolean isStopped = false;
  22.  
  23.     public static void main(String[] args) throws InterruptedException {
  24.         Thread apteka = new Thread(new Apteka());
  25.         Thread man = new Thread(new Person(), "Мужчина");
  26.         Thread woman = new Thread(new Person(), "Женщина");
  27.  
  28.         apteka.start();
  29.         man.start();
  30.         woman.start();
  31.  
  32.         Thread.sleep(1000);
  33.         isStopped = true;
  34.     }
  35.  
  36.     public static class Apteka implements Runnable {
  37.         @Override
  38.         public void run()
  39.         {
  40.  
  41.             while (!isStopped) {
  42.                 drugsController.buy(getRandomDrug(),getRandomCount());
  43.                 try
  44.                 {
  45.                     Thread.sleep(300);
  46.                 } catch (InterruptedException e) {
  47.                 }
  48.             }
  49.         }
  50.     }
  51.  
  52.     public static class Person implements Runnable {
  53.         @Override
  54.         public synchronized void run()
  55.         {
  56.             while (!isStopped) {
  57.                 drugsController.sell(getRandomDrug(),getRandomCount());
  58.                 waitAMoment();
  59.             }
  60.         }
  61.     }
  62.  
  63.     public static int getRandomCount() {
  64.         return (int) (Math.random() * 3) + 1;
  65.     }
  66.  
  67.     public static Drug getRandomDrug() {
  68.         int index = (int) ((Math.random() * 1000) % (drugsController.allDrugs.size()));
  69.         List<Drug> drugs = new ArrayList<Drug>(drugsController.allDrugs.keySet());
  70.         return drugs.get(index);
  71.     }
  72.  
  73.     private static void waitAMoment() {
  74.         try {
  75.             Thread.sleep(100);
  76.         } catch (InterruptedException e) {
  77.         }
  78.     }
  79. }
  80. /*---------------------------------------------------------*/
  81. package com.javarush.test.level17.lesson10.home03;
  82.  
  83. import java.util.HashMap;
  84. import java.util.Map;
  85.  
  86. public class DrugsController {
  87.     public static Map<Drug, Integer> allDrugs = new HashMap<Drug, Integer>();   // <Лекарство, Количество>
  88.  
  89.      static   {
  90.         Drug panadol = new Drug();
  91.         panadol.setName("Панадол");
  92.         allDrugs.put(panadol, 5);
  93.  
  94.         Drug analgin = new Drug();
  95.         analgin.setName("Анальгин");
  96.         allDrugs.put(analgin, 18);
  97.  
  98.         Drug placebo = new Drug();
  99.         placebo.setName("Плацебо");
  100.         allDrugs.put(placebo, 1);
  101.     }
  102.  
  103.     public synchronized void sell(Drug drug, int count) {
  104.         String name = Thread.currentThread().getName();
  105.         if (!allDrugs.containsKey(drug)) {
  106.             System.out.println("Нет в наличии");
  107.         }
  108.         Integer currentCount = allDrugs.get(drug);
  109.         if (currentCount < count) {
  110.             System.out.println(String.format("%s хочет %s %d шт. В наличии - %d", name, drug.getName(), count, currentCount));
  111.         } else {
  112.             allDrugs.put(drug, (currentCount - count));
  113.             System.out.println(String.format("%s купил(а) %s %d шт. Осталось - %d", name, drug.getName(), count, (currentCount - count)));
  114.         }
  115.     }
  116.  
  117.     public synchronized void buy(Drug drug, int count) {
  118.         System.out.println("Закупка " + drug.getName() + " " + count);
  119.  
  120.         if (!allDrugs.containsKey(drug)) {
  121.             allDrugs.put(drug, 0);
  122.         }
  123.         Integer currentCount = allDrugs.get(drug);
  124.         allDrugs.put(drug, (currentCount + count));
  125.     }
  126. }
  127. /*---------------------------------------------------------*/
  128. package com.javarush.test.level17.lesson10.home03;
  129.  
  130. public class Drug {
  131.     private String name;
  132.     private String description;
  133.  
  134.     public String getName() {
  135.         return name;
  136.     }
  137.  
  138.     public void setName(String name) {
  139.         this.name = name;
  140.     }
  141.  
  142.     public String getDescription() {
  143.         return description;
  144.     }
  145.  
  146.     public void setDescription(String description) {
  147.         this.description = description;
  148.     }
  149. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement