现在的位置: 首页 > 综合 > 正文

java守护线程读取配置文件

2013年09月14日 ⁄ 综合 ⁄ 共 1860字 ⁄ 字号 评论关闭

java守护线程读取配置文件

对于某些应用需要实时读取配置文件,但是读取的频率非常高,比如1秒100次以上,修改配置文件的频率远远低于读取频率。此时如果当程序执行的时候每次都
读取配置文件,那么系统的io可能会有些压力,因此可以做一个守护线程每隔一段时间(例如1分钟)读取一次配置文件,代码直接取最新的配置文件的值来执
行,这样既降低了读取配置文件的频率又获得了较好的实时性。
代码如下:
java 代码
 
  1. import
     java.io.InputStream;  
  2. import
     java.util.Properties;  
  3.   
  4. /**
     
  5.  * 系统配置文件类
     
  6.  * @author sunbin
     
  7.  *
     
  8.  */
      
  9. public
     
    class
     Configation 
    extends
     Thread {  
  10.       
  11.     //静态属性类
      
  12.     private
     
    static
     Properties p;  
  13.       
  14.     /**
     
  15.      * 默认构造方法
     
  16.      */
      
  17.     public
     Configation(){  
  18.         //
      
  19.     }  
  20.       
  21.     /**
     
  22.      * 继承Thread必须要实现的方法
     
  23.      */
      
  24.     public
     
    void
     run(){  
  25.         while
    (
    true
    ){  
  26.             //获取classpath中配置文件
      
  27.             InputStream in = Configation.class
    .getClassLoader().getResourceAsStream(
    "config.properties"
    );  
  28.             if
     (p == 
    null
    ){  
  29.                 p = new
     Properties();  
  30.             }  
  31.             try
    {  
  32.                 p.load(in); 
  33.                 in.close();
  34.                 Thread.sleep(10000
    );
    //休眠10秒后重新读取配置文件
      
  35.             }catch
    (Exception e){  
  36.                 e.printStackTrace();  
  37.             }  
  38.         }  
  39.     }  
  40.       
  41.     /**
     
  42.      * 获取配置文件的实例
     
  43.      * @return
     
  44.      */
      
  45.     public
     Properties getProperties(){  
  46.         return
     p;  
  47.     }  
  48.       
  49.     /**
     
  50.      * 测试主程序
     
  51.      * @param args
     
  52.      */
      
  53.     public
     
    static
     
    void
     main(String[] args){  
  54.         Configation c = new
     Configation();  
  55.         c.setDaemon(true
    );
    //设置线程为守护线程
      
  56.         c.start();//启动线程
      
  57.         try
     {  
  58.             Thread.sleep(3000
    );  
  59.         } catch
     (InterruptedException e) {  
  60.             e.printStackTrace();  
  61.         }  
  62.         //重复打印配置文件的值,当修改配置文件后1秒立即生效
      
  63.         while
    (
    true
    ){  
  64.             Properties p = c.getProperties();  
  65.             System.out.println(p.getProperty("com.test.a"
    ));  
  66.         }  
  67.           
  68.     }  
  69.   
  70. }  

其中c.setDaemon(true)设置线程为守护线程,关于守护线程可以参考http://www.google.cn/search?complete=1&hl=zh-CN&q=java+%E5%AE%88%E6%8A%A4%E7%BA%BF%E7%A8%8B&meta=&aq=t&oq=java+%E5%AE%88%E6%8A%A4

抱歉!评论已关闭.