/* * Java code by HauLV * Class: SE1009 * Student Code: SE1009 */ package Store; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Shal */ class Store { private String productName; private boolean available; public synchronized void put(String newProduct) { this.productName = newProduct; } public synchronized String get() { return productName; } public boolean isAvailable() { return available; } public void setAvailable(boolean available) { this.available = available; } } class Producer extends Thread { private Store myStore; private String[] availableProduct; Random r = new Random(); public Producer(Store myStore, String[] availableProduct) { this.myStore = myStore; this.availableProduct = availableProduct; } @Override public void run() { try { while (myStore.isAvailable() == false) { String s = availableProduct[r.nextInt(availableProduct.length)]; myStore.put(s); myStore.setAvailable(true); System.out.println("New Product available: " + s); sleep(1000); } } catch (Exception e) { } } } class Seller extends Thread { private Store myStore; public Seller(Store myStore) { this.myStore = myStore; } @Override public void run() { try { while (myStore.isAvailable() == true) { System.out.println("Product sold: " + myStore.get()); myStore.setAvailable(false); sleep(1000); } } catch (Exception e) { } } } public class MyApp { public static void main(String[] args) { //shared object Store myStore = new Store(); String[] availableProduct = {"Computer", "Printer", "Laptop", "Tablet", "Mobile", "Scanner"}; Producer p = new Producer(myStore, availableProduct); Seller s = new Seller(myStore); p.start(); s.start(); } }