我正在開發一些必須讀取日誌文件的程序,我認爲我在其中構建了一個智能機制,結果代碼甚至沒有編譯...Thread.sleep的中斷處理調用Thread.sleep
我做了一個大的設計缺陷:如何解決它?
public class Reader implements Runnable {
private volatile boolean isReading;
private final File file;
public Reader(final File file) {
this.file = file;
}
@Override
public void run() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException ex) {
throw new IllegalStateException("bf4logreader.Reader.run: File has not been found. file = " + file);
}
while (isReading) {
String line = null;
try {
line = reader.readLine();
} catch (IOException ex) {
throw new IllegalStateException("bf4logreader.Reader.run: Something went wrong when reading file. file = " + file);
}
if (line == null) {
//No new lines
long startSleepTime = System.currentTimeMillis();
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException ex) {
if (isReading) {
//Not supposed to be interrupted
Thread.sleep(System.currentTimeMillis() - startSleepTime);
}
else {
try {
//Needs to shutdown
reader.close();
} catch (IOException ex1) {
Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
}
else {
//Process new lines
System.out.println("Line: " + line);
}
}
}
public void shutdown() {
isReading = false;
}
}
我認爲是聰明的,讓線程睡覺的時候,它仍然不得不睡覺,如果它被不正當地打斷。不過,我當然可以不在這一方做這個,因爲它需要Thread.sleep
的InterrruptedException
再次處理。
我認爲它需要轉換到一些while
循環,但究竟我該如何做到這一點?
編輯:對不起,我忘了把這個想法背後的這個計劃。但是我想要實時監控一個日誌文件,所以它永遠不會停止讀取文件,除非我在關閉消息中指出這種情況。
嘗試拋出整個'if(line == null)'部分。 'reader.readLine()'應該阻塞,直到有東西要讀。 – zapl
@zapl沒有達到文件結尾。 –
我會假設一旦一個線程中斷,它應該停止做它正在做的事情。 –