我已经基于Observer设计模式编写了一个自定义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");
您可以这样使用Producer-Consumer-Pattern:
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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句