我有一个LinkedBlockingQueue,任意选择的容量为10,输入文件有1000行。我在服务类的ExecutorService
方法中有一个main
- 类型变量,据我所知,它首先处理 - 使用Executors.newSingleThreadExecutor()
- 一个线程来调用buffer.readline( )直到文件line == null
,然后在使用Executors.newSingleThreadExecutor()
的循环内处理 - 十个线程来处理行并将它们写入输出文件,直到!queue.take().equals("Stop")
。但是,在向文件写入一些行之后,当我处于调试模式时,我看到队列的容量最终达到max(10),并且处理线程不执行queue.take()
。所有线程都处于running
状态,但进程在queue.put()
之后停止。什么会导致这个问题,是否可以使用线程池或多个ExecutorService
处理程序变量的某种组合而不是单个变量来解决?
服务中main
方法的当前状态概述:
//app settings to get values for keys within a properties file
AppSettings appSettings = new AppSettings();
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10);
maxProdThreads = 1;
maxConsThreads = 10;
ExecutorService execSvc = null;
for (int i = 0; i < maxProdThreads; i++) {
execSvc = Executors.newSingleThreadExecutor();
execSvc.submit(new ReadJSONMessage(appSettings,queue));
}
for (int i = 0; i < maxConsThreads; i++) {
execSvc = Executors.newSingleThreadExecutor();
execSvc.submit(new ProcessJSONMessage(appSettings,queue));
}
阅读方法代码:
buffer = new BufferedReader(new FileReader(inputFilePath));
while((line = buffer.readLine()) != null){
line = line.trim();
queue.put(line);
}
处理和编写代码:
while(!(line=queue.take()).equals("Stop")){
if(line.length() > 10)
{
try {
if(processMessage(line, outputFilePath) == true)
{
++count;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public boolean processMessage(String line, String outputFilePath){
CustomObject cO = new CustomObject();
cO.setText(line);
writeToFile1(cO,...);
writeToFile2(cO,...);
}
public void writeOutputAToFile(CustomObject cO,...){
synchronized(cO){
...
org.apache.commons.io.FileUtils.writeStringToFile(...)
}
}
public void writeOutputBToFile(CustomObject cO,...){
synchronized(cO){
...
org.apache.commons.io.FileUtils.writeStringToFile(...)
}
}
答案 0 :(得分:0)
在处理和编写代码中..确保所有资源都正确关闭。可能由于线程一直在运行而且ExecutorService无法找到空闲线程,资源可能无法正常关闭...