zoukankan      html  css  js  c++  java
  • 一个基于生产者消费者原理的日志系统

    简单的框架,功能未实现

    /**
    * 这个类是个日志系统的简单框架,使用阻塞队列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();
          }
         }
        }
       }
    }
    }

  • 相关阅读:
    POJ 1815 求最小点割(拆点+枚举割边)
    POJ 2391 floyd + 拆点构图 + 二分 + 最大流
    POJ 1966 去掉最少的点使得图不连通(最小点割)
    sgu 194 无源汇的上下界可行流
    POJ 2396 有源汇的上下界可行流(好题)
    DIV水平垂直居中
    The Struts dispatcher cannot be found
    Introduction to 3D Game Programming with Direct X 9.0c读书笔记(1)
    Chapter 5Looking Through a Filter(如何将纹理坐标变换到屏幕坐标)
    Chapter 6Blurring Things Up之Do It Twice
  • 原文地址:https://www.cnblogs.com/macula7/p/1960504.html
Copyright © 2011-2022 走看看