Java Threads Implementation The Java code in Chapter 6 Section 6.6.2 (Synchroniz
ID: 3598182 • Letter: J
Question
Java Threads Implementation
The Java code in Chapter 6 Section 6.6.2 (Synchronization with Semaphores in Java), is only a high-level sketch with some Java code and is not complete. For more details on threads, refer to Chapter 6 and Appendix B in the textbook. You are required to complete the program of a program that implements the solution to the Producer-Consumer problem.
Implement the shared buffer as an array of type char. The Producer and Consumer objects must each display when they have accessed the shared buffer. You may simplify the problem by defining a buffer with a single text character.
-Provide a well-define structure of the Java code to submit.
-Include appropriate comments to clarify your implementation.
-Include course, section, assignment, and your name in the code.
-Indicate the code that you added and show the results.
-You may use (but need to include the reference).
-Show the appropriate computer output compilation and running of the program.
claee Soaaphoro private int Bo; publie aynchronixed void vnit) i avait catch OException e) and zhile } { Syetoa,exit(0);}; and ait public oyachronized void signalo t notifyO: constructor public Seraphore 00a-i tral; int intval) // initialize attributeeD Wond class Seapbore Asme that the producer and consmer pracese are implermented as thrends and the bafer is implemented as anaTray ofsi. The producer is deined with the fnllawing clnss, which inberits the ins Thread: 140 Chapter 6 Synchronizaion Principles // Rtd Ctrtatreetor public void xunci i pty.vzls(); // acquir·excluaiu acceaa utex.ignalo full.igna10; // 1ntreamt f1·lats ond ile log In a imlar mann, he consamur ia deined by the sollowing cas, which inberits exxtende) the Ja claes Thread frll dcor pmhltc runo vile (r) t utex.vieo increseas ety alota and wbile loop nd shite 6.6 Synchronization Case Studies 141 The main clsss defices method ain, which crestea and initializee the semsphore objeets, ecates the two thread objocts (prodacer and consamer abjects), and starts cxerution the thread abjes ltatic fiaal ias y _ 100; // 4ebur of aleza ia biffe: public static void Lain 8tring LrgaU) Predacar ie, full. spty Prodeeer pred- prod. starto ocun.startc //codzoiExplanation / Answer
package pocker;
import java.util.Date;
class Semaphore {
private int sem;
//
public synchronized void swait() {
while ( sem <= 0) {
try {
wait (500);
} catch (Exception e) { System.exit(0);};
}// II end while
sem--; // II decrease value of sem
}// end swait
//
public synchronized void signal() {
sem++;
notify();
} // end signal
//
// constructor
public Semaphore ( int intval) {
sem = intval; // initialize attribute sem
} // end class Semaphore
}
public class Solution{
public static void main(String args[]) {
//instantiate (create) buffer shared by Producer & Consumer
Buffer sharedBuffer = new BoundedBuffer();
// create the producer and consumer threads
Thread producerThread = new Thread(new Producer(sharedBuffer));
Thread consumerThread = new Thread(new Consumer(sharedBuffer));
//start() method allocates memory for a new thread in the JVM,
//and calls the run() method
producerThread.start();
consumerThread.start();
}
}
//*****************************************************************
/**
* An interface for buffers
*
*/
interface Buffer{
/**
* insert an item into the Buffer.
* Note this may be either a blocking
* or non-blocking operation.
*/
public abstract void insert(Object item);
/**
* remove an item from the Buffer.
* Note this may be either a blocking
* or non-blocking operation.
*/
public abstract Object remove();
}
//******************************************************************
/**
* This program implements the bounded buffer using shared memory.
*/
class BoundedBuffer implements Buffer{
private static final int BUFFER_SIZE = 500; //max size of buffer array
private int count; //number of items currently in the buffer
private int in; // points to the next free position in the buffer
private int out; // points to the first filled position in the buffer
private Object[] buffer; //array of Objects
private Semaphore mutex; //provides limited access to the buffer (mutual exclusion)
private Semaphore empty; //keep track of the number of empty elements in the array
private Semaphore full; //keep track of the number of filled elements in the array
public BoundedBuffer(){
// buffer is initially empty
count = 0;
in = 0;
out = 0;
buffer = new Object[BUFFER_SIZE];
mutex = new Semaphore(1); //1 for mutual exclusion
empty = new Semaphore(BUFFER_SIZE); //array begins with all empty elements
full = new Semaphore(0); //array begins with no elements
}
// producer calls this method
public void insert(Object item) {
empty.swait(); //keep track of number of empty elements (value--)
//This provides synchronization for the producer,
//because this makes the producer stop running when buffer is full
mutex.swait(); //mutual exclusion
// add an item to the buffer
++count;
buffer[in] = item;
//modulus (%) is the remainder of a division
//for example, 0%3=0, 1%3=1, 2%3=2, 3%3=0, 4%3=1, 5%3=2
in = (in + 1) % BUFFER_SIZE;
//buffer information feedback
if (count == BUFFER_SIZE){
System.out.println("BUFFER FULL "
+ "Producer inserted "" + item
+ "" count=" + count + ", "
+ "in=" + in + ", out=" + out);
}
else{
System.out.println("Producer inserted "" + item
+ "" count=" + count + ", "
+ "in=" + in + ", out=" + out);
}
mutex.signal(); //mutual exclusion
full.signal(); //keep track of number of elements (value++)
//If buffer was empty, then this wakes up the Consumer
}
// consumer calls this method
public Object remove() {
Object item=null;
/*
while (count == 0){
//if nothing in the buffer, then do nothing
//the buffer array cannot be used (because empty)
}
*/
full.swait(); //keep track of number of elements (value--)
//This provides synchronization for consumer,
//because this makes the Consumer stop running when buffer is empty
mutex.swait(); //mutual exclusion
// remove an item from the buffer
--count;
item = buffer[out];
//modulus (%) is the remainder of a division
//for example, 0%3=0, 1%3=1, 2%3=2, 3%3=0, 4%3=1, 5%3=2
out = (out + 1) % BUFFER_SIZE;
//buffer information feedback
if (count == 0){
System.out.println("BUFFER EMPTY "
+ "Consumer removed "" + item
+ "" count=" + count + ", "
+ "in=" + in + ", out=" + out);
}
else{
System.out.println("Consumer removed "" + item
+ "" count=" + count + ", "
+ "in=" + in + ", out=" + out);
}
mutex.signal(); //mutual exclusion
empty.signal(); //keep track of number of empty elements (value++)
//if buffer was full, then this wakes up the Producer
return item;
}
}
//***************************************************************
/**
* This is the producer thread for the bounded buffer problem.
*/
class Producer extends Thread{
private Buffer buffer;
public Producer(Buffer b) {
buffer = b;
}
public void run(){
Date message;
while (true) {
System.out.println("Producer napping");
SleepUtilities.nap();
// produce an item & enter it into the buffer
message = new Date();
System.out.println("Producer produced "" + message + """);
buffer.insert(message);
}
}
}
//*******************************************************
/**
* This is the consumer thread for the bounded buffer problem.
*/
class Consumer extends Thread{
private Buffer buffer;
public Consumer(Buffer b) {
buffer = b;
}
public void run(){
Date message = null;
while (true){
System.out.println("Consumer napping");
SleepUtilities.nap();
// consume an item from the buffer
System.out.println("Consumer wants to consume");
message = (Date)buffer.remove();
System.out.println("Consumer consumed "" + message + """);
}
}
}
//*********************************************************
/**
* Utilities for causing a thread to sleep.
* Note, we should be handling interrupted exceptions
* but choose not to do so for code clarity.
*
*/
class SleepUtilities{
private static final int NAP_TIME = 5; //max nap time in seconds
/**
* Nap between zero and NAP_TIME seconds.
*/
public static void nap() {
nap(NAP_TIME);
}
/**
* Nap between zero and duration seconds.
*/
public static void nap(int duration) {
int sleeptime = (int) (NAP_TIME * Math.random() );
System.out.println("Nap for " + sleeptime + " seconds");
//Causes the currently executing thread to sleep (cease execution)
//for the specified number of milliseconds,
//subject to the precision and accuracy of system timers and schedulers.
try { Thread.sleep(sleeptime*1000); }
catch (InterruptedException e) {
//method sleep() throws InterruptedException - if any thread has interrupted the current thread.
System.out.println("ERROR in nap(): " + e);
}
}
}
/* output:-
Producer napping
Consumer napping
Nap for 4 seconds
Nap for 4 seconds
Consumer wants to consume
Producer produced "Sun Oct 22 22:08:20 IST 2017"
Producer inserted "Sun Oct 22 22:08:20 IST 2017" count=1, in=1, out=0
Producer napping
Nap for 0 seconds
BUFFER EMPTY Consumer removed "Sun Oct 22 22:08:20 IST 2017" count=0, in=1, out=1
Consumer consumed "Sun Oct 22 22:08:20 IST 2017"
Consumer napping
Nap for 2 seconds
Producer produced "Sun Oct 22 22:08:20 IST 2017"
Producer inserted "Sun Oct 22 22:08:20 IST 2017" count=1, in=2, out=1
Producer napping
Nap for 0 seconds
Producer produced "Sun Oct 22 22:08:20 IST 2017"
Producer inserted "Sun Oct 22 22:08:20 IST 2017" count=2, in=3, out=1
Producer napping
Nap for 4 seconds
Consumer wants to consume
Consumer removed "Sun Oct 22 22:08:20 IST 2017" count=1, in=3, out=2
Consumer consumed "Sun Oct 22 22:08:20 IST 2017"
Consumer napping
Nap for 3 seconds
Producer produced "Sun Oct 22 22:08:24 IST 2017"
Producer inserted "Sun Oct 22 22:08:24 IST 2017" count=2, in=4, out=2
Producer napping
Nap for 4 seconds
Consumer wants to consume
Consumer removed "Sun Oct 22 22:08:20 IST 2017" count=1, in=4, out=3
Consumer consumed "Sun Oct 22 22:08:20 IST 2017"
Consumer napping
Nap for 0 seconds
Consumer wants to consume
BUFFER EMPTY Consumer removed "Sun Oct 22 22:08:24 IST 2017" count=0, in=4, out=4
Consumer consumed "Sun Oct 22 22:08:24 IST 2017"
Consumer napping
Nap for 3 seconds
..........continue until you terminate the program.
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.