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?
There are several problems with your code.
First, I think you should lookup what a static variable is. As it is, all your PrintRequests have the same id, I don't think that's what you want.
Also, your line that generates the sleep duration only generates number between 0 and 1000. This means that a job lasts less than a second, and your output may not look like what you expect.
Change your line to
duration = (int)(1000 + (Math.random()*5000));
This gave me the following output
Printing 0
Printing 2
Printing 1
Printing 4
Printing 5
Printing 6
Printing 7
Printing 8
Printing 3
Printing 9
Completed printing 6
Completed printing 4
Completed printing 8
Completed printing 2
Completed printing 9
Completed printing 3
Completed printing 1
Completed printing 0
Completed printing 7
Completed printing 5
You may ask : why isn't printing in order ?
That's because you cannot control sequentially the order in which Java will launch your threads in a loop like you've made. If you really want to, you will have to add some more mechanisms to enhance that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With