Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Bag {
- private int sweets, in, out;
- public boolean occupied = false;
- public Bag() {
- sweets = in = out = 0;
- }
- public synchronized void addItem() {
- sweets++;
- in++;
- }
- public synchronized void removeItem() {
- sweets--;
- in--;
- }
- public synchronized void printDelta() {
- System.out.println("Delta = " + (in-out-sweets) + " Sweets = " + sweets);
- }
- }
- class Parent extends Thread {
- private Bag bag;
- public Parent(Bag bag) {
- this.bag = bag;
- }
- public void run() {
- while(bag.occupied) {
- try {
- wait();
- } catch (InterruptedException e) { }
- }
- bag.addItem();
- bag.occupied = true;
- notifyAll();
- }
- }
- class Child extends Thread {
- private Bag bag;
- public Child(Bag bag) {
- this.bag = bag;
- }
- public void run() {
- while(!bag.occupied) {
- try {
- wait();
- } catch (InterruptedException e) { }
- }
- bag.removeItem();
- bag.occupied = false;
- notifyAll();
- }
- }
- public class Sweets {
- public static void main(String[] args) throws InterruptedException {
- Bag bag = new Bag();
- Child cthread = new Child(bag);
- Parent pthread = new Parent(bag);
- cthread.start();
- pthread.start();
- while(true) {
- Thread.sleep(2000);
- bag.printDelta();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement