Create the Producer class. It must implement the Runnable interface. Write a constructor that initializes all four instance variables sizeOfJobs,numberOfJobs,delayBetweenJobs,producerName. The run method must generate a certain number of print jobs, based on the numberOfJobs attribute. Give each of these jobs a name based on the producerName and the number of the job. The number of pages in the print job is specified by the sizeOfJobs attribute. Add the print job to the printer manager via the addJob method. This method might throw an FullQueueException, write code to handle this occurrance. Print out a message that the producer is adding a job to the print queue. Between print jobs the producer must sleep based on the delayBetweenJobs attribute
时间: 2024-03-13 10:45:03 浏览: 61
Sure! Here is an example implementation of the Producer class that meets your requirements:
```java
import java.util.Random;
public class Producer implements Runnable {
private int sizeOfJobs;
private int numberOfJobs;
private int delayBetweenJobs;
private String producerName;
private PrinterManager printerManager;
public Producer(int sizeOfJobs, int numberOfJobs, int delayBetweenJobs, String producerName, PrinterManager printerManager) {
this.sizeOfJobs = sizeOfJobs;
this.numberOfJobs = numberOfJobs;
this.delayBetweenJobs = delayBetweenJobs;
this.producerName = producerName;
this.printerManager = printerManager;
}
@Override
public void run() {
Random rand = new Random();
for (int i = 1; i <= numberOfJobs; i++) {
PrintJob job = new PrintJob(producerName + " Job #" + i, rand.nextInt(sizeOfJobs) + 1);
try {
printerManager.addJob(job);
System.out.println(producerName + " is adding a job to the print queue.");
} catch (FullQueueException e) {
System.out.println(producerName + " could not add a job to the print queue: " + e.getMessage());
}
try {
Thread.sleep(delayBetweenJobs);
} catch (InterruptedException e) {
System.out.println(producerName + " was interrupted while waiting to add a job to the print queue.");
}
}
}
}
```
This class takes in four parameters in its constructor: `sizeOfJobs`, `numberOfJobs`, `delayBetweenJobs`, and `producerName`. These correspond to the instance variables you mentioned in your question. It also takes in a `PrinterManager` object, which is used to add jobs to the print queue.
The `run` method generates `numberOfJobs` print jobs, with names based on the `producerName` and the job number. The number of pages in each job is randomly generated between 1 and `sizeOfJobs`. The job is added to the printer manager via the `addJob` method, which might throw a `FullQueueException`. If this occurs, the method catches the exception and prints out a message indicating that the job could not be added to the print queue. Between jobs, the producer sleeps for `delayBetweenJobs` milliseconds.
I hope this helps! Let me know if you have any further questions.
阅读全文