FileHandler
一旦线程完成或强制完成,我想关闭所有s 。
我创建了一个closeLogger
函数,但它似乎没有被调用
,因为我看到该文件仍被锁定在文件夹中。
- 问题是什么?
- 如果我在eclipse中强行终止执行,我也可以处理吗?
我的代码如下:
public class Passenger extends Thread {
private Logger logger;
public Passenger() throws SecurityException, IOException, InterruptedException {
logger = Logger.getLogger(String.format("Passenger%sLogger", name));
FileHandler fileHandler = new FileHandler(String.format(".\\Logs\\PassengerLogs\\passenger_%s.txt", name), true);
fileHandler.setFormatter(new LogFormatter());
logger.addHandler(fileHandler);
}
@Override
public void run() {
try {
goToStation();
waitForTaxi();
if (passengerState == PassengerState.WatingInQueue) {
goHome();
} else { // already in taxi
synchronized (this) {
wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
closeLogger();
}
}
private void closeLogger() {
Logger logger = getLogger();
java.util.logging.Handler[] handlers = logger.getHandlers();
for (java.util.logging.Handler h : handlers) {
try {
h.close();
} catch (SecurityException e) {}
}
}
}