我有數百個文件需要處理。我一次只做一個文件,花費30分鐘。如何保持線程列表?
我想我可以在10個線程,10個文件在同一時間做這個處理,我也許能做到3分鐘,而不是30
我的問題是,什麼是「正確」的方式來管理我的10個線程?當一個完成後,創建一個新的最大數量爲10.
這是我迄今爲止...這是「正確」的方式來做到這一點?
public class ThreadTest1 {
public static int idCounter = 0;
public class MyThread extends Thread {
private int id;
public MyThread() {
this.id = idCounter++;
}
public void run() {
// this run method represents the long-running file processing
System.out.println("I'm thread '"+this.id+"' and I'm going to sleep for 5 seconds!");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I'm thread '"+this.id+"' and I'm done sleeping!");
}
}
public void go() {
int MAX_NUM_THREADS = 10;
List<MyThread> threads = new ArrayList<MyThread>();
// this for loop represents the 200 files that need to be processed
for (int i=0; i<200; i++) {
// if we've reached the max num of threads ...
while (threads.size() == MAX_NUM_THREADS) {
// loop through the threads until we find a dead one and remove it
for (MyThread t : threads) {
if (!t.isAlive()) {
threads.remove(t);
break;
}
}
}
// add new thread
MyThread t = new MyThread();
threads.add(t);
t.start();
}
}
public static void main(String[] args) {
new ThreadTest1().go();
}
}
不要。使用JDK提供的線程池。 – 2014-10-30 14:33:47
您應該閱讀@Robert Hume,「首先,線程無法加速代碼的執行。」 http://programmers.stackexchange.com/questions/97615/what-can-multiple-threads-do-that-a-single-thread-cannot – rottenoats 2014-10-30 14:37:17
感謝您的建議,我會谷歌線程池。但是,我在做這件事的方式有什麼特別的「錯誤」嗎?我想學習,謝謝! – 2014-10-30 14:37:19