gpt4 book ai didi

java - 在不同的线程上执行每个日志请求

转载 作者:行者123 更新时间:2023-11-30 03:35:20 25 4
gpt4 key购买 nike

我编写了一个基于观察者设计模式的自定义 MyLogger 库。我想要实现的是:每次调用 writeLog(LOG_LEVEL,"Text") 方法时,我希望它在新线程中执行。有人可以建议实现这一目标的方法是什么吗?就像我应该在哪里创建线程一样。

这就是我的 Logger 调用的样子。

public class Logger extends Subject{
void writeLog(String type, String message)
{ setData(message);
notifyy(type);
}

}

这就是我调用 writeLog 的方式

appLogger.writeLog("ERROR", "This is error");

最佳答案

您可以像这样使用生产者-消费者模式:

public class Logger {

/**
* The ExecutorService runs the Thread that processes the logs.
*/
private final ExecutorService loggingService = Executors.newSingleThreadExecutor();

/**
* A queue that contains the logs.
*/
final BlockingQueue<YourLogObject> logs = new LinkedBlockingQueue<>();

/**
* Creates a new Logger object and starts the Thread that processes the logs.
*/
public Logger() {
loggingService.submit(new Runnable() {

@Override
public void run() {
try {
for (;;) {
final YourLogObject log = logs.take();

// setData(log.getMessage());
// notify(log.getLevel());
}
} catch (final InterruptedException e) {
e.printStackTrace();
return;
}
}

});
}

/**
* Creates a new YourLogObject from the given parameters and puts it at the end of the queueu.
*/
public void writeLog(final String level, final String message) {
final YourLogObject log = new YourLogObject(level, message);

try {
logs.put(log);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}

/**
*
*/
public void shutdown() {
loggingService.shutdownNow();
}

}

public class YourLogObject {

private final String level;

private final String message;

public YourLogObject(final String level, final String message) {
this.level = level;
this.message = message;
}

public String getLevel() {
return level;
}

public String getMessage() {
return message;
}

}

关于java - 在不同的线程上执行每个日志请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28084622/

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