Java Swing 多線程加載圖片(保證順序一致)
大二的時(shí)候做的課程設(shè)計(jì),圖片管理器,當(dāng)時(shí)遇到圖片很多的文件夾,加載順序非常慢。雖然嘗試用多個(gè)Thread加載圖片,卻無法保證圖片按順序加載。直到今天學(xué)會(huì)了使用Callable接口和Future接口,于是心血來潮實(shí)現(xiàn)了這個(gè)功能。
廢話不多說,看代碼。
多線程加載圖片(核心):
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<JLabel> loadImages(String path) {
List<JLabel> 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<Future<MyLabel>> futures = new ArrayList<>();
for (final File f : files) {
Future<MyLabel> future = executor.submit(() -> {
return new MyLabel(f.getName(), f.getAbsolutePath());
});
futures.add(future);
}
//等待所有并發(fā)加載返回結(jié)果
try {
for (Future<MyLabel> 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<JLabel> 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<MyLabel>{
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;
}
}
}
Swing界面:
package com.lin.imagemgr;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class MainFrame extends JFrame{
private static final long serialVersionUID = 1L;
private JTextField pathField;
private JButton showBtn;
private JPanel contentPanel;
public void init() {
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
topPanel.setPreferredSize(new Dimension(800, 40));
pathField = new JTextField(50);
showBtn = new JButton("顯示圖片");
topPanel.add(pathField);
topPanel.add(showBtn);
getContentPane().add(BorderLayout.NORTH, topPanel);
contentPanel = new JPanel();
contentPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
contentPanel.setPreferredSize(new Dimension(750, 1800));
JScrollPane jsp = new JScrollPane(contentPanel);
getContentPane().add(BorderLayout.CENTER, jsp);
showBtn.addActionListener((e) -> {
try {
loadImages();
} catch (Exception ex) {
ex.printStackTrace();
}
});
setSize(800, 650);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public void loadImages() {
contentPanel.removeAll();
String path = pathField.getText();
long start = System.currentTimeMillis();
List<JLabel> images = ImageMgr.getInstance().loadImages(path);
for (JLabel label :images) {
contentPanel.add(label);
}
contentPanel.updateUI();
long end = System.currentTimeMillis();
System.out.println("加載需要" + (end - start) + "毫秒!");
}
public static void main(String[] args) {
new MainFrame().init();
}
}
運(yùn)行結(jié)果


在我的電腦上,加載92張圖片并渲染到界面上,總共花了1568毫秒。大家可以找一個(gè)圖片很多的文件夾,嘗試加載大量圖片的情況。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于Spring概念模型:PathMatcher 路徑匹配器
這篇文章主要介紹了Spring概念模型:PathMatcher 路徑匹配器,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
詳解使用Spring AOP和自定義注解進(jìn)行參數(shù)檢查
本篇文章主要介紹了詳解使用Spring AOP和自定義注解進(jìn)行參數(shù)檢查,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-04-04
SpringBoot詳細(xì)講解多個(gè)配置文件的配置流程
SpringBoot項(xiàng)目是一個(gè)標(biāo)準(zhǔn)的Maven項(xiàng)目,它的配置文件需要放在src/main/resources/下,其文件名必須為application,其存在兩種文件形式,分別是properties和yaml(或者yml)文件2022-06-06
詳解Spring Boot工程集成全局唯一ID生成器 UidGenerator的操作步驟
本文就在項(xiàng)目中來集成 UidGenerator這一工程來作為項(xiàng)目的全局唯一 ID生成器。接下來通過實(shí)例代碼給大家詳解詳解Spring Boot工程集成全局唯一ID生成器 UidGenerator的操作步驟,感興趣的朋友一起看看吧2018-10-10
MybatisPlus為何可以不用@MapperScan詳解
這篇文章主要給大家介紹了關(guān)于MybatisPlus為何可以不用@MapperScan的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用MybatisPlus具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2023-04-04
Java實(shí)現(xiàn)簡(jiǎn)單酒店管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)簡(jiǎn)單酒店管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05
Java實(shí)現(xiàn)音頻轉(zhuǎn)文本的示例代碼(語音識(shí)別)
Java中實(shí)現(xiàn)音頻轉(zhuǎn)文本通常涉及使用專門的語音識(shí)別服務(wù),本文主要介紹了Java實(shí)現(xiàn)音頻轉(zhuǎn)文本的示例代碼(語音識(shí)別),具有一定的參考價(jià)值,感興趣的可以了解一下2024-05-05

