Question

Java Programming: Make a Java program with two processes, a producer and a consumer. If you...

Java Programming:

Make a Java program with two processes, a producer and a consumer. If you want to use another language, clear it with me first.

The producer process consists of a loop that writes the loop count (a value from 0 to 4) into a variable that it shares with the consumer process (this variable is to be initialized to 100). On each pass through the loop, before the producer writes into the shared variable, it does a random wait of from one to three seconds (compute a new random wait value on each pass through the loop). The loop is to be executed five times.

The consumer process consists of a loop that reads the variable it shares with the producer five times and computes the sum of the values it has read. On each pass through the loop before it reads the shared variable, it does a random wait of from one to three seconds (compute a new random value on each pass through the loop). When the loop finishes, the program is to write the sum into a file.

You must run the program twice. Note that the output from the runs will almost certainly be different if you have written your program correctly. Place a zip file with the code, a copy of the output from each of your runs (the output file must be to a data file and not a screen shot). Also include a word or text file with your observations on the assignment: What did you notice about the runs? What if anything did you learn doing this assignment? Roughly how long (in hours) did the assignment take?

Please put comments at the top of your program with your name, the date, the assignment number, and a brief description of the program. I also want to see comments within the program. The first items in your data file and observations file must be your name and the assignment number (have your program output this information into your output file). Note, I do not want screen shots, your program must output to a data file which is to be sent to me. You are to zip your files together and place the zip file.

The contents of you output file should look something like this (where ### is your computed sum). If you have the output from both runs in the same file, you do not need to repeat your name and the assignment number.

John Smith

Assignment #2

The sum is ###

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Dear Student,

Kindly go through given code below and let me know if you have any further queries. The Chegg portal allows only attachment of images and in order to get the specified format, you need to copy the code below and create new project in java and submit the assignment according to the given requirement.

ProducerConsumer.java

/*
* Main class to demonstrate concept of Producer-Consumer
* This class creates instance of Producer and Consumer class and
* holds the holds the value set by Producer class and returns the
* value to the consumer upon request.
*/

import java.util.Random;   // Import the random number generator pacakge

public class ProducerConsumer{
   private int value = 100;   // Initialize the value
  
   public static void main(String[] args) throws InterruptedException {
       ProducerConsumer pc = new ProducerConsumer();   // Create instance of this class
       Producer producer = new Producer(pc);           // Create instance of Producer class
       Consumer consumer = new Consumer(pc);           // Create instance of Consumer class
      
       producer.start();       // Start the producer thread
       consumer.start();       // Start the consumer thread
   }
  
   // Wait the execution for random duration
   private void userWait()
   {
       // Generate random number to wait before populating data
       Random random = new Random();
       int waitDuration = random.nextInt(3) + 1;
      
       // Wait for given number of duration
       try {
           wait(waitDuration);
       } catch (InterruptedException e) { }
   }
  
   // Function to set the value
   public synchronized void set(int value)
   {
       userWait();               // Wait the execution for random duration
       this.value = value;       // Set the value
   }
  
   // Function to get the stored value
   public synchronized int get()
   {
       userWait();           // Wait the execution for random duration
       return value;       // Return the stored value
   }
}

Producer.java

/*
* Producer class to demonstrate the concept of Producer.
*/

public class Producer extends Thread {
   private ProducerConsumer pc;   // Holds the instance of Producer Consumer main class
  
   // Constructor to initialize
   public Producer(ProducerConsumer pc)
   {
       this.pc = pc;
   }
  
   // Implementation of run() function, executed on calling start() function
   public void run()
   {
       // Set all the 5 values
       for(int i=0; i<5; i++)
       {
           pc.set(i);
       }
   }
}

Consumer.java

/*
* Consumer class to demonstrate the concept of Consumer.
*/

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class Consumer extends Thread{
   private ProducerConsumer pc;   // Holds the instance of Producer Consumer main class
  
   // Constructor to initialize
   public Consumer(ProducerConsumer pc)
   {
       this.pc = pc;
   }
  
   // Implementation of run() function, executed on calling start() function
   public void run()
   {
       int sumResult = 0;   // Variable to hold the sum value
      
       // Loop 5 times and get the sum using the producer stored values
       for(int i=0; i<5; i++)
       {
           sumResult = sumResult + pc.get();
       }
      
       // Store the result into text file
       try {
           FileWriter fileWriter = new FileWriter("result.txt");
           BufferedWriter buffWriter = new BufferedWriter(fileWriter);
          
           buffWriter.write("John Smith\nAssignment #1\nThe sum is " + sumResult);
          
           if(buffWriter != null)
               buffWriter.close();
          
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
}

Output:

Add a comment
Know the answer?
Add Answer to:
Java Programming: Make a Java program with two processes, a producer and a consumer. If you...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Make a Java, program with two processes, a producer and a consumer. The producer process consists...

    Make a Java, program with two processes, a producer and a consumer. The producer process consists of a loop that writes the loop count (a value from 0 to 4) into a variable that it shares with the consumer process (this variable is to be initialized to 100). On each pass through the loop, before the producer writes into the shared variable, it does a random wait of from one to three seconds (compute a new random wait value on...

  • Producer and Consumer Code in C++ The program will contain two methods- one each for the...

    Producer and Consumer Code in C++ The program will contain two methods- one each for the producer and consumer. Both methods share access to an integer array buffer of size 50 with all values initialized to 0 at the beginning and an integer variable counter initialized to 0. As given below, the producer accesses the buffer elements and updates the element to 1 ( indicating production). The consumer changes a buffer elements to 0 (indicating consumption). Enhancements and modifications: You...

  • please put the comment each line, make sure i will have output too. write a program,...

    please put the comment each line, make sure i will have output too. write a program, Summarize (Summarize.java), containing the main() method, that first writes 10,000 random positive double type numbers, to the full accuracy of the number (15/16 decimal places), to a text file named DataValues.txt, one number per line. The program must then close that file, and reopen it for reading. Read back the values from the file and write the following information to a file named Summary.txt:...

  • Java. (20 pts)          Write a program that reads all the numbers from the file mynums.dat...

    Java. (20 pts)          Write a program that reads all the numbers from the file mynums.dat and prints out the sum of the positive values from the file. Assume that the file contains only numeric values. You must output an error if the file can't be opened. You must write the complete program and the output when the program runs successfully must conform exactly to the sample output. Bonus ( 5 pts). Output an error if the file contains non-numeric...

  • In Java. Write a program in a single file that: Main: Creates 10 random doubles, all...

    In Java. Write a program in a single file that: Main: Creates 10 random doubles, all between 1 and 11, Calls a class that writes 10 random doubles to a text file, one number per line. Calls a class that reads the text file and displays all the doubles and their sum accurate to two decimal places. There has to be three classes, main for create random numbers, one to write , one to read all in the same file...

  • CSIT 345 Lab 2 Process Programming Your lab requirement is to write program codes for 3.21 and sh...

    *Help Please with the code** CSIT 345 Lab 2 Process Programming Your lab requirement is to write program codes for 3.21 and shared memory program for producer and consumer as shown in the following. You can start with the code provided in the virtual machine in the virtual box you installed. The code can be found in /home/oscreader/osc9e-src/ch3 a. For 3.21, you can start with the newprocposix.c and modify the code to meet your requirement. Then type: gcc neypCOCROSİS.c to...

  • IN JAVA. Write a program that reads a file (provided as attachment to this assignment) and...

    IN JAVA. Write a program that reads a file (provided as attachment to this assignment) and writes the file to a different file with line numbers inserted at the beginning of each line. For example if file input is: This is a test File output should be 1. This is a test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BELOW FROM NOTEPAD FILE. This file contains lines of text to determine if you can properly read and write from a file.

  • Lab Assignment 4B Modify your program in Lab Assignment 4A to throw an exception if the...

    Lab Assignment 4B Modify your program in Lab Assignment 4A to throw an exception if the file does not exist. An error message should result.   Use the same file name in your program as 4A, however, use the new input file in 4B assignment dropbox. Lab 4A: Write a program that reads a file (provided as attachment to this assignment) and writes the file to a different file with line numbers inserted at the beginning of each line. Test with...

  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • Using c++ write a program using a class that has   data members ID#,NAME, SALARY, YEAR_HIRED. This...

    Using c++ write a program using a class that has   data members ID#,NAME, SALARY, YEAR_HIRED. This program must 1) write 10 blank records to a random access file. You must enter data for 4 of these records. 2) allow the user to output the name, salary, hire_date for a selected record 3) allow the user to change the name, salary, or hire_date for a selected record. 4) allow the user to input a complete record to replace one of the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT