这个问题有许多相似的主题,但我还没有找到解决方案。基本上,我所做的是异步更新ArrayList。然而,这并不是真正相关的,因为无论是否同步或异步运行都会发生高内存使用,但是当我同步运行时,它比不同步运行时更重要(仍然是重要的imo)(可能是因为BufferedImage)存储在多个线程上,而不是多次在单个线程上覆盖。)
这是我为异步部分所做的工作。忍受我,第一次我做过异步任务,所以它可能很糟糕,但它会运行。
public void updateAllShows() {
// I find it runs faster even when thread amount > # of threads from CPU
ExecutorService ex = Executors.newFixedThreadPool(array size)
// All the Future tasks we execute later
ArrayList> tasks = new ArrayList
// This holds the new MyShowComp that all the Futures calculate
ArrayList tempArray = new ArrayList
for (MyShowComp comp : array) {
final MyShowComp c = comp;
FutureTask> t = new FutureTask(new Runnable() {
@Override
public void run() {
// I'll detail this method in a moment
tempArray.add(updateShowAsync(c,false));
}
}, null);
// Now that future task is created, we add it to the list of tasks
tasks.add(t);
}
// Cycle through and execute every stored task
for (FutureTasks)
executor.execute(task);
executor.shutdown();
if (shutdown finished)
array = tempArray;
// Do some sorting and add to panel
}
那很简单。现在麻烦的部分,我更新了节目的图像:
public MyShowComp updateShowAsync(MyShowComp c, boolean bool) {
//
// Bunch of irrelevant code, already tested, doesn't affect memory usage
//
BufferedImage img = null;
// We pull th