this is an exercise where i have 1 Producer and N Consumer ( fill and remove Water into an WaterTank ) which i implemented in the shown code.
Now the text of the exercise says: Filling an additional tank: This way u can be sure that water won't be put in and taken away at the same time. Or you could as well say that water can only be taken away if there is a putOperation.
I don't understand it. I have synchronized on an private final object so the first part ( won't be put and taken away at the same time ) doesn't happen anyway. Also there is no need for an additional Watertank that way.
The second part where it will be taken at the same time it will be put i also quite don't understand. Do i need Semaphores or Reeantrantlock or anything?
I know i have to put an WaterTank Object into my already existing WaterTank as far as i understand.
Thy for any help :)
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));
}
}
}