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();
          }
         }
        }
       }
    }
    }

  • 相关阅读:
    五、异步任务编排CompletableFuture
    四、fork/join框架
    三、阻塞等待异步结果FutureTask
    二、synchronized同步锁
    一、Java多线程基础
    6. ZigZag Conversion (字符串的连接)
    5. Longest Palindromic Substring (DP)
    4. Median of Two Sorted Arrays (二分法;递归的结束条件)
    3. Longest Substring Without Repeating Characters (ASCII码128个,建立哈西表)
    2. Add Two Numbers
  • 原文地址:https://www.cnblogs.com/macula7/p/1960504.html
Copyright © 2011-2022 走看看