探索java多线程(连载)1 守护线程(一)

2014-11-24 00:34:43 · 作者: · 浏览: 2

在java中有一类线程,专门在后台提供服务,此类线程无需显式关闭,当程序结束了,它也就结束了,这就是守护线程 daemon thread。如果还有非守护线程的线程在执行,它就不会结束。 守护线程有何用处呢?让我们来看个实践中的例子。

在我们的系统中经常应用各种配置文件(黑名单,禁用词汇),当修改配置文件后,一般要重启服务,系统才能够加载;当重启服务的代价比较高的情况下,这种加载方式不能满足我们的要求,这个时候守护线程该发挥它的作用了,它可以实时加载你的配置文件,无需重启。(当然,相当重要的配置文件,不推荐实时加载)

package com.ikon.thread.daemon;

import java.io.File;
import java.util.*;

/** *//**
* 文件监测
* @author ikon99999
*
*/
public abstract class FileWatchdog extends Thread {


static final public long DEFAULT_DELAY = 20*1000;


protected HashMap fileList;

protected long delay = DEFAULT_DELAY;

boolean warnedAlready = false;

boolean interrupted = false;

public static class Entity
{
File file;
long lastModify;
Entity(File file,long lastModify)
{
this.file = file;
this.lastModify = lastModify;
}
}

protected FileWatchdog() {
fileList = new HashMap ();
setDaemon(true);
}


public void setDelay(long delay) {
this.delay = delay;
}

public void addFile(File file)
{
fileList.put(file.getAbsolutePath(),new Entity(file,file.lastModified()));
}

public boolean contains(File file)
{
if( fileList.get(file.getAbsolutePath()) != null) return true;
else return false;
}

abstract protected void doOnChange(File file);

protected void checkAndConfigure() {
HashMap map = (HashMap)fileList.clone();
Iterator it = map.values().iterator();

while( it.hasNext())
{

Entity entity = (Entity)it.next();

boolean fileExists;
try {
fileExists = entity.file.exists();
} catch(SecurityException e)
{
System.err.println ("Was not allowed to read check file existance, file:["+ entity.file .getAbsolutePath() +"].");
interrupted = true;
return;
}

if(fileExists)
{

long l = entity.file.lastModified(); // this can also throw a SecurityException
if(l > entity.lastModify) { // however, if we reached this point this
entity.lastModify = l; // is very unlikely.
newThread(entity.file);
}
}
else
{
System.err.println ("["+entity.file .getAbsolutePath()+"] does not exist.");
}
}
}

private void newThread(File file)
{
class MyThread extends Thread
{
File f;
public MyThread(File f)
{
this.f = f;
}

public void run()
{
doOnChange(f);
}
}

MyThread mt = new MyThread(file);
mt.start();
}

public void run()
{
while(!interrupted) {
try {
Thread.currentThread().sleep(delay);
} catch(InterruptedException e) {
// no interruption expected
}
checkAndConfigure();
}
}
}

FileWatchdog是个抽象类,本身是线程的子类;在构造函数中设置为守护线程;
此类用hashmap维护着一个文件和最新修改时间值对,checkAndConfigure()方法用来检测哪些文件的修改时间更新了,如果发现文件更新了则调用doOnChange方法来完成监测逻辑;doOnChange方法是我们需要实现的;看下面关于一个黑名单服务的监测服务:

1package com.ikon.thread.daemon;
2
3import java.io.File;
4
5/** *//**
6 * 黑名单服务
7 * @a