我一直收到以下错误:
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");
而且我很确定我已经抛出了这个错误。只有在添加以下行时才会出现此错误:Thread.sleep(1000)
这是我的代码:
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");
}
}
答案 0 :(得分:0)
因为你的printRequest方法抛出一个InterruptedException,它必须被main捕获,或者被main抛出......以下任何一个答案都应该有效......
<p>You Rolled a {{ yourRoll }}</p>