2014-10-30 2 views
0

처리 할 파일이 수백 개 있습니다. 한 번에 하나씩 각 파일을 처리하는데 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(); 
    } 

} 
+4

하지 않습니다. JDK에서 제공하는 스레드 풀을 사용하십시오. –

+0

@Robert Hume을 읽어야합니다. "우선 스레드가 코드 실행 속도를 높일 수 없습니다." http://programmers.stackexchange.com/questions/97615/what-can-multiple-threads-do-that-a-single-thread-cannot – rottenoats

+0

제안 해 주셔서 감사 드리며, Google 스레드 풀을 사용하겠습니다. 하지만 내가하고있는 방식에 대해 구체적으로 "잘못된"것이 있습니까? 나는 배우고 싶다, 고마워! –

답변

2

스레드를 관리하려면 ExecutorService을 사용할 수 있습니다.

그리고 파일 처리 작업을 반복적으로 실행하기 위해 스레드 실행 방법에 while 루프를 추가 할 수 있습니다. 또한 BlockingQueue 사용법을 읽을 수 있습니다. 스레드간에 새 파일 (작업)을 할당하는 것이 완벽하게 맞을 것이라고 생각합니다.

0

나는 그것이 열려있는 경우 Camel's File component을 사용하는 것이 좋습니다. 구성 요소는 동시성이있는 모든 문제를 처리하여 여러 스레드가 동일한 파일을 처리하지 않도록합니다. 코드를 멀티 스레드로 만드는 가장 큰 과제는 스레드가 상호 작용하지 않도록하는 것입니다. 이것을 프레임 워크가 처리하도록하십시오.

예 :

from("file://incoming?maxMessagesPerPoll=1&idempotent=true&moveFailed=failed&move=processed&readLock=none") 
     .threads(10).process() 
관련 문제