I'm currently programming a program for university. In this program I have to create three Consumerthreads which compete around a stock of products.
For the stock of products, I used a HashMap<String, Integer> which is saved in a class called marketplace.
My Consumer thread:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class consumer implements Runnable{
List<String> productTypes = new ArrayList<>();
Map<String, Integer> productsBought = new HashMap<>();
marketplace marketplace;
public consumer( marketplace marketplace) {
this.marketplace = marketplace;
}
@Override
public void run() {
buy();
this.marketplace.addProductsBought(this.productsBought);
}
public synchronized void buy(){
int bought =0;
this.productTypes = this.marketplace.getProductTypes();
for(int i = 0; i<this.productTypes.size(); i++){
String productType = this.productTypes.get(i);
bought = this.marketplace.buyProduct(productType);
this.productsBought.put(productType, bought);
}
}
}
Now to my question, how can I program the threads in a way that they really compete around the product, because when I initialize the threads, the first one buys everything and the others get nothing.
The Threads are started like:
Runnable consumerOne = new consumer(marketplace);
Runnable consumerTwo = new consumer(marketplace);
Runnable consumerThree = new consumer(marketplace);
Thread consumerOneThread = new Thread(consumerOne);
Thread consumerTwoThread = new Thread(consumerTwo);
Thread consumerThreeThread = new Thread(consumerThree);
consumerOneThread.start();
consumerTwoThread.start();
consumerThreeThread.start();
There are 6 different types of products in random amounts from 5 to 10 saved in the HashMap in the marketplace object.
Threadpools are not allowed.