因为在编写时疏忽,而使程序僵死,后来才发现是因为 PipeWriter 和 Reader的原因,导致 template.Process 僵死。
如下代码就会这样。
cfg=new Configuration(Configuration.VERSION_2_3_21);
cfg.setDefaultEncoding("utf-8");
cfg.setDirectoryForTemplateLoading(new File("template"));
PipedWriter pw = new PipedWriter();
Reader reader = new PipedReader(pw);
Template tpl=cfg.getTemplate("xxxx.tpl");
Map map....
map.put(.....);
..........
tpl.process(map, pw); //在此处线程暂停了
pw.close();
//这里需要另起一个线程用于reader 读取数据
doProcess(reader);
其实原因就是 Pipe 缓冲区满了,tpl.process处理的时候暂停了。所以把程序改一下,增加一个后台线程来处理Freemarker的tpl.process 就可以了。 很简单。
例如:把 template.process放入子线程也可以,write也在子线程中关闭。
reader=.....
pw=.......
Thread th=new Runnable(){
public void Run()
{
tpl.process(map, pw);
pw.close();
}
}
th.start();
while(reader.readLine()!=null)
{
...........
}
reader.close();