Advertisement
Guest User

Untitled

a guest
Aug 19th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1. class Bag {
  2.  
  3.     private int sweets, in, out;
  4.     public boolean occupied = false;
  5.     public Bag() {
  6.         sweets = in = out = 0;
  7.  
  8.     }
  9.  
  10.     public synchronized void addItem() {
  11.  
  12.         sweets++;
  13.         in++;
  14.     }
  15.  
  16.     public synchronized void removeItem() {
  17.  
  18.         sweets--;
  19.         in--;
  20.     }
  21.  
  22.     public synchronized void printDelta() {
  23.  
  24.         System.out.println("Delta = " + (in-out-sweets) + " Sweets = " + sweets);
  25.     }
  26.  
  27. }
  28. class Parent extends Thread {
  29.  
  30.     private Bag bag;
  31.     public Parent(Bag bag) {
  32.         this.bag = bag;
  33.     }
  34.  
  35.     public void run() {
  36.  
  37.         while(bag.occupied) {
  38.             try {
  39.                 wait();
  40.             } catch (InterruptedException e) { }
  41.         }
  42.  
  43.         bag.addItem();
  44.         bag.occupied = true;
  45.         notifyAll();
  46.     }
  47. }
  48.  
  49. class Child extends Thread {
  50.  
  51.     private Bag bag;
  52.     public Child(Bag bag) {
  53.         this.bag = bag;
  54.     }
  55.  
  56.     public void run() {
  57.         while(!bag.occupied) {
  58.             try {
  59.                 wait();
  60.             } catch (InterruptedException e) { }
  61.         }
  62.  
  63.         bag.removeItem();
  64.         bag.occupied = false;
  65.         notifyAll();
  66.     }
  67. }
  68.  
  69. public class Sweets {
  70.  
  71.     public static void main(String[] args) throws InterruptedException {
  72.  
  73.         Bag bag = new Bag();
  74.         Child cthread = new Child(bag);
  75.         Parent pthread = new Parent(bag);
  76.  
  77.         cthread.start();
  78.         pthread.start();
  79.  
  80.         while(true) {
  81.             Thread.sleep(2000);
  82.             bag.printDelta();
  83.         }
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement