十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
大二的时候做的课程设计,图片管理器,当时遇到图片很多的文件夹,加载顺序非常慢。虽然尝试用多个Thread加载图片,却无法保证图片按顺序加载。直到今天学会了使用Callable接口和Future接口,于是心血来潮实现了这个功能。

废话不多说,看代码。
多线程加载图片(核心):
package com.lin.imagemgr;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import net.coobird.thumbnailator.Thumbnails;
public class ImageMgr {
private static ImageMgr instance = new ImageMgr();
private ImageMgr() {}
public static ImageMgr getInstance() {
return instance;
}
//线程池
private ExecutorService executor = Executors.newFixedThreadPool(8);
public List loadImages(String path) {
List images = new ArrayList<>();
File file = new File(path);
if (!file.isDirectory()) {
throw new RuntimeException("need directory!");
}
File[] files = file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
//thumbnail只支持jpg??
if (name.endsWith(".jpg")) {
return true;
}
return false;
}
});
//并发加载图片,并使用Future保存加载结果
List> futures = new ArrayList<>();
for (final File f : files) {
Future future = executor.submit(() -> {
return new MyLabel(f.getName(), f.getAbsolutePath());
});
futures.add(future);
}
//等待所有并发加载返回结果
try {
for (Future future : futures) {
MyLabel icon = future.get();
images.add(icon);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//Java8使用stream API 进行排序
List sortedList = images.stream().sorted().collect(Collectors.toList());
return sortedList;
}
//继承JLabel并实现Comparable接口,从而对JLabel进行排序
private static class MyLabel extends JLabel implements Comparable{
private static final long serialVersionUID = 1L;
private String fileName;
public MyLabel(String fileName, String fullPath) {
this.fileName = fileName;
//使用thumbnailator生成缩略图
try {
BufferedImage bufferedImage = Thumbnails.of(fullPath)
.size(100, 120)
.asBufferedImage();
setIcon(new ImageIcon(bufferedImage));
setPreferredSize(new Dimension(100, 120));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public int compareTo(MyLabel o) {
int result = this.fileName.compareTo(o.fileName);
return result;
}
}
}