2 학년에 있었을 때 코스 디자인과 사진 관리자를했습니다. 당시에는 많은 사진이있는 폴더를 만났고 로딩 순서는 매우 느 렸습니다. 여러 스레드로 그림을로드하려고했지만 사진이 순서대로로드 될 것이라고 보장 할 수 없었습니다. 오늘까지 나는 Callable 인터페이스와 미래의 인터페이스를 사용하는 법을 배웠 으므로이 기능을 변덕스럽게 깨달았습니다.
말도 안되는 말을하지 말고 코드를보십시오.
멀티 스레드 이미지 로딩 (Core) :
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.concurrent java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.future; import java.util.stream.collectors; import javax.swing.imageicon; import javax.swing.jlabel imageMgr {private static imagemgr instance = new imagemgr (); private imagemgr () {} public static imagemgr getinstance () {return instance; } // 스레드 풀 개인 executorService executor = executor.newfixedThreadpool (8); 공개 목록 <Jlabel> loadImages (String Path) {list <Jlabel> images = new ArrayList <> (); 파일 = 새 파일 (Path); if (! file.isdirectory ()) {Throw new runtimeexception ( "dectory!"); } file [] files = file.listFiles (new FilEnameFilter () {@Override public boolean accept (파일 DIR, 문자열 이름) {// 썸네일 만 JPG? // 동시에 그림을로드하고 미래를 사용하여 로딩 결과 목록을 저장 <Future <MyLabel >> futures = new ArrayList <> (); for (final file f : files) {Future <MyLabel> Future = Executor.Submit (() -> {return new MyLabel (f.getName (), f.getAbsolutepath ());}); futures.add (미래); } // 결과를 반환하기 위해 모든 동시 부하를 기다리는 대기 {for (future <mylabel> future : futures) {mylabel icon = future.get (); images.add (아이콘); }} catch (InterruptedException e) {e.printstacktrace (); } catch (executionException e) {e.printstacktrace (); } // java8은 스트림 API를 사용하여 목록을 정렬하여 <jlabel> sortedList = images.stream (). sorted (). collect (collectors.tolist ()); SortedList 리턴; } // jlabel을 상속하고 비슷한 인터페이스를 구현하여 jlabel private static class mylabel을 정렬하여 jlabel 구현 <mylabel> {private static final long serialversionuid = 1l; 개인 문자열 파일 이름; public mylabel (String filename, String fullpath) {this.filename = filename; // Thumbnailator를 사용하여 썸네일을 생성하십시오 {bufferedImage bufferedImage = tumlnails.of (fullPath) .Size (100, 120) .asbufferedImage (); seticon (새로운 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); 반환 결과; }}}스윙 인터페이스 :
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.swing.jlabel; javax.swing.jscrollpane; import javax.swing.jtextfield; public class mainframe 확장 jframe {private static final long serialversionuid = 1l; 개인 Jtextfield Pathfield; 개인 Jbutton showbtn; 개인 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 ( "Show Picture"); toppanel.add (pathfield); toppanel.add (showbtn); getContentPane (). Add (BorderLayout.North, TopPanel); ContentPanel = 새로운 jpanel (); ContentPanel.setLayout (New FlowLayout (FlowLayout.Left, 5, 5)); ContentPanel.setPreferredSize (New Dimension (750, 1800)); jscrollpane jsp = 새로운 jscrollpane (contentpanel); getContentPane (). Add (BorderLayout.Center, JSP); showbtn.addactionListener ((e) -> {try {loadimages ();} catch (예외) {ex.printstacktrace ();}}); setsize (800, 650); setDefaultCloseOperation (jframe.exit_on_close); setLocationRelativeto (null); setvisible (true); } public void loadImages () {contentpanel.removeall (); 문자열 path = pathfield.getText (); Long Start = System.CurrentTimeMillis (); List <Jlabel> images = imageMgr.getInstance (). loadImages (path); for (jlabel 레이블 : 이미지) {contentpanel.add (label); } contentPanel.upDateUi (); Long End = System.CurrentTimeMillis (); System.out.println ( "로딩이 필요합니다" + (종료 - 시작) + "milliseconds!"); } public static void main (String [] args) {new Mainframe (). init (); }}실행 결과
내 컴퓨터에서는 92 장의 사진을로드하여 총 인터페이스에 렌더링하는 데 1568 밀리 초가 걸렸습니다. 사진이 많은 폴더를 찾아 많은 사진을로드 할 수 있습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.