您的位置:首页 > 其它

一个基于生产者消费者原理的日志系统

2010-03-13 04:40 357 查看
简单的框架,功能未实现

/**

* 这个类是个日志系统的简单框架,使用阻塞队列blockingqueue来工作

* 该类的记录由一个内部类来实现,该内部类作为一个现场来运行,它从blockingqueue中取出信息来,将其写入到writer中

* 工作过程类似于生产者,消费者原理

* @author 王法波

* @version 1.0

*

*/

public class LoggerService {

/**

* 阻塞队列

*/

private final BlockingQueue<String> queue;

/**

* 内部类对象

*/

private final LoggerThread loggerThread;

/**

* writer对象

*/

private final PrintWriter writer;

/**

* 判定是否关闭

*/

private boolean isShutdown;

/**

* 行数

*/

private int reservations;

/**

* 初始队列长度

*/

private final int SIZE = 100;

/**

* 构造函数

* @throws FileNotFoundException

*/

public LoggerService() throws FileNotFoundException {

queue = new ArrayBlockingQueue<String>(SIZE);

loggerThread = new LoggerThread();

writer = new PrintWriter(new File(""));

}

/**

* 启动消费者线程

*/

public void start() {

loggerThread.start();

}

/**

* 停止线程

*/

public void stop() {

synchronized (this) {

isShutdown = true;

}

loggerThread.interrupt();

}

/**

* 向日志中写入信息

* @param msg

* @throws InterruptedException

*/

public void log(String msg) throws InterruptedException {

synchronized (this) {

if(isShutdown)

throw new IllegalStateException("");

++reservations;

}

queue.put(msg);

}

/**

* 内部类

* @author Administrator

*

*/

private class LoggerThread extends Thread {

public void run() {

while (true) {

synchronized (LoggerService.this) {

if (isShutdown && reservations == 0)

break;

String msg;

try {

msg = queue.take();

synchronized (LoggerService.this) {

--reservations;

}

writer.println(msg);

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

writer.close();

}

}

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: