gpt4 book ai didi

java - 如何在线程中关闭 FileHandlers?

转载 作者:行者123 更新时间:2023-11-30 09:36:59 24 4
gpt4 key购买 nike

我想在线程完成或强制完成后关闭所有 FileHandler
我创建了一个 closeLogger 函数,但它似乎没有被调用
因为我看到文件仍然锁定在文件夹中。

  1. 有什么问题?
  2. 在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) {}
}
}
}

最佳答案

由于您使用 addHandler() 添加处理程序,干净的方法是关闭 () 然后调用 removeHandler()

See removeHandler

此外,从上面的链接复制:

After passing this initial (cheap) test, the Logger will allocate a LogRecord to describe the logging message. It will then call a Filter (if present) to do a more detailed check on whether the record should be published. If that passes it will then publish the LogRecord to its output Handlers. By default, loggers also publish to their parent's Handlers, recursively up the tree.

因此,如果您不删除处理程序,它仍将保留引用。这可能是您的文件仍处于锁定状态的原因。试试这个,让我知道它是否有效!

关于java - 如何在线程中关闭 FileHandlers?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10597447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com