大二的時(shí)候做的課程設(shè)計(jì),圖片管理器,當(dāng)時(shí)遇到圖片很多的文件夾,加載順序非常慢。雖然嘗試用多個(gè)Thread加載圖片,卻無法保證圖片按順序加載。直到今天學(xué)會(huì)了使用Callable接口和Future接口,于是心血來潮實(shí)現(xiàn)了這個(gè)功能。
讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來自于我們對(duì)這個(gè)行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡(jiǎn)單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長(zhǎng)期合作伙伴,公司提供的服務(wù)項(xiàng)目有:主機(jī)域名、雅安服務(wù)器托管、營(yíng)銷軟件、網(wǎng)站建設(shè)、交口網(wǎng)站維護(hù)、網(wǎng)站推廣。廢話不多說,看代碼。
多線程加載圖片(核心):
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 ListloadImages(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; } }); //并發(fā)加載圖片,并使用Future保存加載結(jié)果 List > futures = new ArrayList<>(); for (final File f : files) { Future future = executor.submit(() -> { return new MyLabel(f.getName(), f.getAbsolutePath()); }); futures.add(future); } //等待所有并發(fā)加載返回結(jié)果 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 進(jìn)行排序 List sortedList = images.stream().sorted().collect(Collectors.toList()); return sortedList; } //繼承JLabel并實(shí)現(xiàn)Comparable接口,從而對(duì)JLabel進(jìn)行排序 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; } } }