---
title: "java守护线程读取配置文件"
author: "rainbow686"
date: "2007-11-05T16:09:48Z"
tags: []
slug: "java"
draft: false
lastmod: "2007-11-05T16:09:48Z"
id: 138113
url: "https://rainbow686.iteye.com/blog/138113"
---

对于某些应用需要实时读取配置文件，但是读取的频率非常高，比如1秒100次以上，修改配置文件的频率远远低于读取频率。此时如果当程序执行的时候每次都 读取配置文件，那么系统的io可能会有些压力，因此可以做一个守护线程每隔一段时间（例如1分钟）读取一次配置文件，代码直接取最新的配置文件的值来执 行，这样既降低了读取配置文件的频率又获得了较好的实时性。  
代码如下：

java 代码

 

01. import java.io.InputStream;
02. import java.util.Properties;
03. /\**
04. * 系统配置文件类
05. * @author sunbin
06. \*
07. \*/
08. public class Configation extends Thread {
09. //静态属性类
10. private static Properties p;
11. /\**
12. * 默认构造方法
13. \*/
14. public Configation(){
15. //
16. }
17. /\**
18. * 继承Thread必须要实现的方法
19. \*/
20. public void run(){
21. while(true){
22. //获取classpath中配置文件
23. InputStream in = Configation.class.getClassLoader().getResourceAsStream("config.properties");
24. if (p == null){
25. p = new Properties();
26. }
27. try{
28. p.load(in);
29. Thread.sleep(10000);//休眠10秒后重新读取配置文件
30. }catch(Exception e){
31. e.printStackTrace();
32. }
33. }
34. }
35. /\**
36. * 获取配置文件的实例
37. * @return
38. \*/
39. public Properties getProperties(){
40. return p;
41. }
42. /\**
43. * 测试主程序
44. * @param args
45. \*/
46. public static void main(String\[] args){
47. Configation c = new Configation();
48. c.setDaemon(true);//设置线程为守护线程
49. c.start();//启动线程
50. try {
51. Thread.sleep(3000);
52. } catch (InterruptedException e) {
53. e.printStackTrace();
54. }
55. //重复打印配置文件的值，当修改配置文件后1秒立即生效
56. while(true){
57. Properties p = c.getProperties();
58. System.out.println(p.getProperty("com.test.a"));
59. }
60. }
61. }

其中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](http://www.google.cn/search?complete=1&amp%3Bhl=zh-CN&amp%3Bq=java%20%E5%AE%88%E6%8A%A4%E7%BA%BF%E7%A8%8B&amp%3Bmeta=&amp%3Baq=t&amp%3Boq=java%20%E5%AE%88%E6%8A%A4 "http://www.google.cn/search?complete=1&amp;hl=zh-CN&amp;q=java+%E5%AE%88%E6%8A%A4%E7%BA%BF%E7%A8%8B&amp;meta=&amp;aq=t&amp;oq=java+%E5%AE%88%E6%8A%A4")