×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Hậu Len
Added: May 11, 2016 11:49 AM
Views: 1962
Tags: no tags
  1. /*
  2.  * Java code by HauLV
  3.  * Class: SE1009
  4.  * Student Code: SE1009
  5.  */
  6. package Store;
  7.  
  8. import java.util.Random;
  9. import java.util.logging.Level;
  10. import java.util.logging.Logger;
  11.  
  12. /**
  13.  *
  14.  * @author Shal
  15.  */
  16. class Store {
  17.  
  18.     private String productName;
  19.     private boolean available;
  20.  
  21.     public synchronized void put(String newProduct) {
  22.         this.productName = newProduct;
  23.     }
  24.  
  25.     public synchronized String get() {
  26.         return productName;
  27.     }
  28.  
  29.     public boolean isAvailable() {
  30.         return available;
  31.     }
  32.  
  33.     public void setAvailable(boolean available) {
  34.         this.available = available;
  35.     }
  36.  
  37. }
  38.  
  39. class Producer extends Thread {
  40.  
  41.     private Store myStore;
  42.     private String[] availableProduct;
  43.     Random r = new Random();
  44.  
  45.     public Producer(Store myStore, String[] availableProduct) {
  46.         this.myStore = myStore;
  47.         this.availableProduct = availableProduct;
  48.     }
  49.  
  50.     @Override
  51.     public void run() {
  52.         try {
  53.             while (myStore.isAvailable() == false) {
  54.                 String s = availableProduct[r.nextInt(availableProduct.length)];
  55.                 myStore.put(s);
  56.                 myStore.setAvailable(true);
  57.                 System.out.println("New Product available: " + s);
  58.                 sleep(1000);
  59.             }
  60.         } catch (Exception e) {
  61.         }
  62.     }
  63. }
  64.  
  65. class Seller extends Thread {
  66.  
  67.     private Store myStore;
  68.  
  69.     public Seller(Store myStore) {
  70.         this.myStore = myStore;
  71.     }
  72.  
  73.     @Override
  74.     public void run() {
  75.         try {
  76.  
  77.             while (myStore.isAvailable() == true) {
  78.                 System.out.println("Product sold: " + myStore.get());
  79.                 myStore.setAvailable(false);
  80.                 sleep(1000);
  81.             }
  82.         } catch (Exception e) {
  83.         }
  84.     }
  85. }
  86.  
  87. public class MyApp {
  88.  
  89.     public static void main(String[] args) {
  90.         //shared object
  91.         Store myStore = new Store();
  92.         String[] availableProduct = {"Computer", "Printer", "Laptop", "Tablet", "Mobile", "Scanner"};
  93.         Producer p = new Producer(myStore, availableProduct);
  94.         Seller s = new Seller(myStore);
  95.  
  96.         p.start();
  97.  
  98.         s.start();
  99.     }
  100. }
  101.