Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Develop a multithreaded producer-consumer system where a producer produces a ran

ID: 3760584 • Letter: D

Question

Develop a multithreaded producer-consumer system where a producer produces a random integer number (range 1 to 10).

A consumer guesses this number (5 Guesses), sees if its guess is correct. The consumer counts the number of correct guesses, and clicks a next button in order for the producer to produce another integer so that it can try guessing again.

Note the shared buffer holds only one integer at a time and the number of correct guesses.

The producer and consumer outputs the number of correct/incorrect before finishing. Make sure that the consumer does not consume the same item twice and that the producer does not overwrite an unconsumed item.

Do not use an array-blocking Queue.

In Java.

Explanation / Answer

static int data = 0; static Object obj1 = new Object(); static class Producer implements Runnable { public void run() { produce(); } void produce() { while (true) { if (data < 5){ synchronized(obj1){ System.out.println("Producing Data. Now Data is "+data++); obj1.notifyAll(); } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else{ try { System.out.println("Producer inactive"); synchronized(obj1){ obj1.wait(); } System.out.println("Producer active"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } static class Consumer implements Runnable{ public void run(){ consume(); } void consume() { while (true) { if (data > 0){ synchronized(obj1){ System.out.println("Consuming Data. Now Data is "+data--); obj1.notifyAll(); } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else{ try { System.out.println("Consumer Inactive"); synchronized(obj1){ obj1.wait(); } System.out.println("Consumer Active"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }