我有一個加載速度很慢的程序,我想這是由於我必須在開始時加載的圖像資源數量所致。我認爲多線程會有所幫助,但現在我不太確定。這是我的自動多線程方法。Java - 使用ImageIO進行多線程處理
private static Thread[] t;
private static int currentThreads;
public static void loadWithThreads(Object[] array, IntegerRunnable r) {
final int threads = Runtime.getRuntime().availableProcessors();
t = new Thread[threads];
for (int i = 0; i < threads; i ++) {
t[i] = new Thread("HMediaConverter") {
final int id = currentThreads;
int items = (array.length/threads) * currentThreads;
@Override
public void run() {
super.run();
for (int i = items; i < (items + (array.length/threads)); i ++) {
r.run(i);
}
//Recycle this thread so it can be used for another time.
try {
t[id].join();
lock.notifyAll();
currentThreads --;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t[i].setPriority(Thread.MAX_PRIORITY);
t[i].start();
currentThreads ++;
}
}
這裏是我的圖片加載代碼:
public static ImageIcon loadImageIcon(String path) {
return new ImageIcon(ImageIO.read(Tools.class.getClassLoader().getResource(path));
}
肯定有一種方法可以加快速度?我在一個完美的英特爾i5上運行這個,它不應該這麼慢,所以它一定是我的代碼。
使用'ExecutorService'相反,可能不會解決問題,但它是你正在做什麼,然後有很多清潔現在 – MadProgrammer
另外,一旦'Thread'的'run'方法存在,它就不能重新啓動 – MadProgrammer
@MadProgrammer當我說'run()'方法不可能的時候,我可以問你指的是什麼嗎?重新啓動?我不太明白你在做什麼。並感謝您的快速反饋;我很感激。 – PragmaticObject