Answer to Question #249482 in Java | JSP | JSF for Locos

Question #249482

Write a simulation 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-10-13T00:29:19-0400
import java.util.ArrayList;


public class Main {
	public static void main(String[] args) {
		Market sm = new Market(25);
		sm.farmer("apple");
		sm.farmer("orange");
		sm.farmer("grape");
		sm.farmer("watermelon");
		sm.consumer();
	}
}
class Market{
	private ArrayList<String> fts = new ArrayList<>();
	private int num;
	public Market(int num) {
		if (num > 0) {
			this.num = num;
		} else {
			throw new IllegalArgumentException("Invalid argument");
		}
	} 
	private synchronized boolean isFull() {
		return fts.size() == this.num;
	}


	private synchronized boolean isEmpty() {
		return fts.isEmpty();
	}


	public synchronized void farmer(String ft) {
		if (isFull()) {
			System.out
					.println("No more fruits can be accepted");
			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println("Interruption");
			}
		}
		fts.add(ft);
		System.out.printf("fruit : %s is added %n", ft);
	}


	public synchronized String consumer() {


		if (isEmpty()) {
			System.out.println("No good fruit");
			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println("Interruption");
			}
		}
		
		String cur_fts = fts.remove(0);
		notifyAll();
		return cur_fts;
	}


}

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