WaterTank ProducerConsumer Pattern

时间:2016-01-27 11:58:49

标签: java concurrent-programming

这是一个练习,我有1个制作人和N个消费者(填写并删除Water到WaterTank中),我在显示的代码中实现了。

现在练习的内容说: 填充额外的坦克: 这样你可以确保不会同时放入和带走水。 或者您也可以说,只有在存在putOperation的情况下才能带走水。

我不明白。我已经同步了一个私人的最终对象,所以第一部分(不会同时放置和带走)也不会发生。此外,不需要额外的Watertank。

第二部分将在同一时间拍摄,我也很不明白。我需要信号量或Reeantrantlock或其他什么吗?

据我所知,我知道我必须将WaterTank对象放入我现有的WaterTank中。

你的任何帮助:)

public class WaterTank {

  private final int capacity;
  private int water;
  private final Object synchobj = new Object();

  public WaterTank(int capacit, int wate) {
    this.capacity = capacit;
    this.water = wate;
  }

  public void fillwater(int wata) {

    synchronized (synchobj) {
      if (water + wata > capacity) {
        System.out.println("Cannot fill water!");

      } else {
        water = water + wata;
        System.out.println("FILL::::Capacity: " + capacity + " and Water: " + water);
      }
    }
  }

  public void removewater(int wata) {
    synchronized (synchobj) {
      if (water - wata < 0) {
        System.out.println("Cannot take water!");
      } else {
        water = water - wata;
        System.out.println("REMOVE:::Capacity: " + capacity + " and Water: " + water);
      }
    }
  }
}

public class Producer implements Runnable {
  private final WaterTank T;

  public Producer(WaterTank t) {
    this.T = t;
  }

  @Override
  public void run() {
    while (true) {
      T.fillwater(10);
    }
  }
}

public class Consumer implements Runnable {

  private final WaterTank T;

  public Consumer(WaterTank t) {
    this.T = t;
  }

  @Override
  public void run() {
    while (true) {
      T.removewater(10);
    }
  }
}

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class test {

  public static void main(String[] args) {

    WaterTank F = new WaterTank(100, 0);

    Thread Pro = new Thread(new Producer(F));
    Pro.start();
    ExecutorService exec = Executors.newCachedThreadPool();

    for (int i = 0; i < 5; i++) {
      exec.execute(new Consumer(F));
    }
  }
}

0 个答案:

没有答案