这是一篇很长的文章,所以我不得不说感谢阅读。 我的应用程序应该处理很多声音文件,比方说 4000+。我的第一种方法是加载一定数量(比如 200mb)的声音数据,对其进行处理、写入,然后“清空”数据以让 gc 释放它。但考虑到数据是通过内网加载的,这似乎不是“最好”的方式。 (文件访问速度慢)计算应该从第一个加载的文件开始。为了实现这一点,我将概念更改为一种“生产者/消费者”(我认为)。到目前为止,这是我的类(class):
读者/制作人
public class ReaderThread extends Thread {
List<Long> files;
ConcurrentLinkedQueue<Long> loaded = new ConcurrentLinkedQueue<Long>();
boolean finished = false;
public ReaderThread( List<Long> soundFiles) {
this.files = soundFiles;
}
@Override
public void run() {
Iterator<Long> it = files.iterator();
while(it.hasNext()) {
Long id = it.next();
if (FileLoader.load(id)) {
loaded.add(id);
}
}
finished = true;
}
public Long getNextId() {
while(loaded.isEmpty()) {
if( finished ) {
return null;
}
}
Long id = loaded.poll();
return id;
}
}
这是作者/(不是消费者)
public class WriterThread extends Thread {
ConcurrentLinkedQueue<Long> loaded = new ConcurrentLinkedQueue<Long>();
String directory;
boolean abort = false;
public WriterThread(String directory) {
this.directory = directory;
}
@Override
public void run() {
while(!(abort&&loaded.isEmpty())) {
if(!loaded.isEmpty()) {
Long id = loaded.poll();
FileWriter.write(id, directory);
FileManager.unload(id);
}
}
}
public synchronized void submit(Long id) {
loaded.add(id);
}
public synchronized void halt() {
abort = true;
}
}
这是所有事物聚集在一起的部分:
// Forgive me the "t" and "w". ;-)
t = new ReaderThread(soundSystem,soundfilesToProcess);
w = new WriterThread(soundSystem,outputDirectory );
t.start();
w.start();
long start = System.currentTimeMillis();
while(!abort) {
Long id = t.getNextId();
if(id!=null) {
SoundFile soundFile = soundSystem.getSoundfile(id);
ProcessorChain pc = new ProcessorChain(soundFile, getProcessingChain(), w);
Future<List<ProcessorResult>> result = es.submit(pc);
results.add(result);
}else {
break;
}
}
for( Future<List<ProcessorResult>> result : results) {
List<ProcessorResult> tempResults;
try {
tempResults = result.get();
processResults(tempResults);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
w.halt();
“ProcessorChain”是可运行的。 es.submit -> “es”是一个缓存线程池。
我首先要知道的是天气好不好这种做法是“好”,还是更像是“废话”。它似乎工作得很好,但我对编写器线程没有什么问题,似乎在某些情况下并非所有文件都被写入。 ProcessorChain 在完成工作时调用 writer threads submit 方法。 第二件事是线程安全。我错过了什么吗?
最佳答案
我相信如果每个线程读取、处理然后写入整个声音文件(每个文件一个线程),将会(很多)简单。
您可以使用 Java thread pools并让操作系统/Java VM 并行读取/处理/写入多个文件以提高效率。我可能是错的,但根据您的描述,一个更简单的解决方案就足够了,然后如果需要进一步改进,您可以衡量您的瓶颈。
关于Java Thread Good Practice 这个呀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3303762/