처리 할 파일이 수백 개 있습니다. 한 번에 하나씩 각 파일을 처리하는데 30 분이 걸립니다.스레드 목록을 유지 관리하는 방법은 무엇입니까?
가내가 한 번에 10 개 개의 동시 스레드, 10 개 파일이 처리를 할 수있다 생각하고, 나는 내 질문은 30
대신 3 분 안에 그것을 할 수있을은 무엇이고 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에서 제공하는 스레드 풀을 사용하십시오. –
@Robert Hume을 읽어야합니다. "우선 스레드가 코드 실행 속도를 높일 수 없습니다." http://programmers.stackexchange.com/questions/97615/what-can-multiple-threads-do-that-a-single-thread-cannot – rottenoats
제안 해 주셔서 감사 드리며, Google 스레드 풀을 사용하겠습니다. 하지만 내가하고있는 방식에 대해 구체적으로 "잘못된"것이 있습니까? 나는 배우고 싶다, 고마워! –