Answer to Question #242474 in Java | JSP | JSF for Jerry

Question #242474
Write a simulation java program for the fruit market. The farmer will be able to

produce different types of fruits (apple, orange, grape, and watermelon), and

put them in the market to sell. The market has limited capacity and farmers

have to stand in a queue if the capacity is exceeded to sell their fruits.

Consumers can come to the market any time and purchase their desired fruits;

and if the fruits they want to buy runs out, they are willing to wait until the

supply of that kind is ready. (Hint: implementing this market will encounter

the producer and consumer problem, and it probably needs multiple buffers

for different kinds of fruits).
1
Expert's answer
2021-09-26T18:50:07-0400
import java.util.ArrayList;

class Market {
	private ArrayList<String> fruits = new ArrayList<>();
	private int fruitsNumber;
	public Market(int fruitsNumber) {
		if (fruitsNumber > 0) {
			this.fruitsNumber = fruitsNumber;
		} else {
			throw new IllegalArgumentException("This argument is not valid");
		}
	}
	private synchronized boolean isFull() {
		return fruits.size() == this.fruitsNumber;
	}
	private synchronized boolean isEmpty() {
		return fruits.isEmpty();
	}
       public synchronized void farmer(String fruit) {
		if (isFull()) {
			System.out
					.println("We can not accept more fruites at the moment !!");
			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println("Interruption");
			}
		}
		fruits.add(fruit);
		System.out.printf("fruit : %s is added !!!%n", fruit);
	}


	public synchronized String consumer() {
		if (isEmpty()) {
			System.out.println("we don't have any goods yet");
			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println("interruption occure !!!");
			}
		}
		String currentFruitRecusted = fruits.remove(0);
		notifyAll();
		return currentFruitRecusted;
	}
}
public class Main {
	public static void main(String[] args) {
		Market superMarket = new Market(10);
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS