I have this assignment which is to simulate the behaviour of a printer where print jobs may be submitted to a printer with varying time intervals or simultaneously. So, thread.start()
must be used here, and the printer will take a job from the printer queue and print it, while the rest of the other jobs wait for their turn.
In total I only need to write 3 classes, the Admin
class, the PrintRequest
class and the Printer
class.
Here is my codes:
public class Admin{
public static void main(String[] args){
Printer printer = new Printer();
for(int x=0; x<10;x++){
PrintRequest printRequest = new PrintRequest(x,printer);
printRequest.start();
}
}
}
public class PrintRequest extends Thread {
private static int duration;
private static int id;
private static Printer printer;
public PrintRequest(int id, Printer printer){
duration = (int)Math.ceil(Math.random()*1000);
this.id = id;
this.printer = printer;
}
public void run(){
printer.printJob(id, duration);
}
}
public class Printer{
public static synchronized void printJob(int id, int duration){
System.out.println("Printing " + id);
try{Thread.sleep(duration);}
catch(InterruptedException ex){System.out.println(ex.getMessage());}
System.out.println("Completed printing " + id);
}
}
There is some problems with the output, it is not the desired output that I want -- printing from ID 0-10. Instead the output is as such:
So what is the problem in my code? I would think it is the problem with the Admin
class loop but how should I improve on it such that it can function correctly?