在不同的线程上执行每个日志记录请求

时间:2015-01-22 08:57:20

标签: java multithreading observer-pattern

我编写了一个基于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");

2 个答案:

答案 0 :(得分:1)

您可以使用ExecutorService

// Somewhere in your logging framework
ExecutorService service = Executors.new...(); // Choose the one you want
...

public MessageRelayingTask implements Runnable {
    // private fields
    ...

    public MessageRelayingTask(String type, String message) {
         ...
    }

    @Override
    public void run() {
        setData(message);
        notifyy(type);
    }     
}

public class Logger extends Subject implements Runnable {
    void writeLog(String type, String message) {
        service.submit(new MessageRelayingTask(type, message));
    }
}

一些可以帮助您入门的指示:

答案 1 :(得分:1)

你可以使用像这样的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;
    }

}