I keep getting the following error:
PrintServerV1.java:63: error: unreported exception InterruptedException; must be caught or declared to be thrown
server.printRequest("homework7.txt");
^
PrintServerV1.java:64: error: unreported exception InterruptedException; must be caught or declared to be thrown
server.printRequest("assignment4.txt");
^
PrintServerV1.java:65: error: unreported exception InterruptedException; must be caught or declared to be thrown
server.printRequest("speech.pdf");
And I am pretty sure that I have thrown the error. This error only happens when add the following line: Thread.sleep(1000)
Here is my code:
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
import static java.lang.System.out;
public class PrintServerV1 implements Runnable {
private static final Queue<String> requests = new LinkedList<String>();
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void printRequest(String s) throws InterruptedException {
lock.lock();
try {
out.println("Adding print request for: " + s);
requests.add(s);
condition.signal();
} finally { lock.unlock(); Thread.sleep(1000);}
}
public void sendRequest() throws InterruptedException {
lock.lock();
try {
while (requests.size() == 0) {
condition.await();
}
out.println("Sending Request to printer");
Thread.sleep(1000);
while (!requests.isEmpty()) {
realPrint(requests.remove());
}
} finally {
lock.unlock();
}
}
private void realPrint(String s) throws InterruptedException {
// do the real work of outputting the string to the screen
out.println("Currently printing: " + s);
Thread.sleep(1000);
}
public void run() {
try {
sendRequest();
} catch (InterruptedException exception) {}
}
public static void main(String[] args) {
PrintServerV1 server = new PrintServerV1();
new Thread(server).start();
server.printRequest("homework7.txt");
server.printRequest("assignment4.txt");
server.printRequest("speech.pdf");
}
}