java-日志服务使用多线程

本文介绍了一种基于生产者-消费者模式的日志服务设计,包括使用阻塞队列进行日志传递、确保子任务原子性的方法以及通过ExecutorService管理线程生命周期的策略。

1、写入日志的活动作为生产者,读取日志的活动做为消费者。

2、保证创建新日志消息的各个子任务是原子的。但不希望在消息加入队列时加锁,即将put方法和take方法放在同步之外。

public class LogService{

   private finalBlockingQueue<String> queue;

   privatefinal LoggerThread loggerThread;

   private final PrintWriterwriter;

   @GuardBy("this") privateboolean isShutdown;

   @GuardBy("this")private intreservations;  

  

   public vidstart(){loggerThread.start();}

   public viod stop(){

      syndhronized (this) (isShutdown=true;)

      loggerThread.interrupt();

   }

  

   public void log(String msg)throws InterruptedException{

      synchronized (this){

          if (isShutdown) throws newIllegalStateException(...);++revations;

      }

      queue.put(msg);

   }

  

   private class loggerThreadextends Thread{

        public void run(){

             try{

                   while (true){

                      try{

                            synchronized (LogService.this){

                                 if (isShutdown&&reservations==0)break;

                            }

                      }

                   }catch (InterruptedException e){}

             }

        }

        finally{

                 writer.close();

        }

   }

  

 

}

3、封装ExecutorService通过增加链接,把所有权链从应用程序扩展到了服务,再到线程;每个链上的成员管理它的拥有的服务或线程的生命周期

public class Logservice{

    privatefinal ExecutorService exec=newSingleThreadExecutor();

    ...

    publicvoid start(){}

   

    publicvoid stop() throws InterruptedException{

       try{

         exec.shutdown();

         exec.awaitTermination(TIMEOUT,UNIT);

       }

       finally{

            writer.close();

        }

    }

    publicvoid log(String msg){

            try{

             }

              catch(RejectedExecutionException ignored) {}

    }

}

4、 一个可识别的对象,置于队列中,意味着当你得到它时,停止一切工作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值