2010-04-17 5 views
2

가능한 한 빨리 데이터베이스 테이블에서 작업 큐를 처리하는 동시에 작업을 처리 할 스레드 수를 제한하려고합니다.
고정 크기 스레드 풀을 과 함께 사용하고 있습니다. Executors.newFixedThreadPool (N);Java의 스레드 풀에 사용 가능한 스레드가 있는지 확인하는 방법

스레드 풀이 꽉 찼는지를 알고 싶습니다. 현재 50 개의 스레드가 실행 중이라는 것을 의미합니다. 그렇다면 스레드를 실행하기 전에 스레드를 사용할 수있을 때까지 기다릴 것입니다. 메인 스레드를 자고있는 대신 새로운 하나. 내가하고 싶은 것이의

코드 :

ExecutorService executor = Executors.newFixedThreadPool(N); 
ResultSet results; 

while(true) { 
    results = getWaitingTasksStmt.executeQuery(); 

    while(results.next() && executor.notFull()) { 
     executor.submit(new thread(new runnableInheritedClass(results))); 
    } 
} 
+0

실행 프로그램이 스레드를 작성합니다. runnables/callables를 거기에 넣어야합니다. N이 50으로 설정되고 50이 제한 인 경우 고정 스레드 풀이 새 스레드를 생성하지 않습니다. – mkorpela

답변

7

Thread 개체를 집행자에게 제출하면 안됩니다.이 개체는 전체 목적을 부정합니다. Runnable 개체를 제출하고 ExecutorThread 처리에 대해 걱정해야합니다. 모든 스레드가 사용 중이면 자동으로 Runnable을 대기열에 넣고 하나의 작업이 완료되면 대기열에서 대기중인 작업을 가져옵니다.

그래서 코드는 더 다음과 같아야합니다

ExecutorService executor = Executors.newFixedThreadPool(N); 

ResultSet results = getWaitingTasksStmt.executeQuery(); 

while(results.next()) { 
    executor.submit(new RunnableInheritedClass(results))); 
} 

executor.shutdown(); 
executor.awaitTermination(10, TimeUnit.MINUTES); 

이 모든 작업에 10 분, 완료 당신의 situatioin 경우와 neccesary 조정할 수 있습니다. 영원히 기다리는 것은 실망 스럽기 때문에 일에 합당한 시간 초과를 생각하십시오.

6

ExecutorService 당신을 위해 모든 작업을 수행합니다. 모든 스레드가 현재 다른 작업에서 사용되고있는 경우 새 작업이 대기열에 배치되고 나중에 처리됩니다. 모든 스레드가 현재 사용중인 경우에도 새 작업을 제출할 때 주 스레드가 차단되지 않습니다.

ExecutorService executor = Executors.newFixedThreadPool(N); 
ResultSet results; 

while(true) { 
    results = getWaitingTasksStmt.executeQuery(); 

    while(results.next()) { 
     // If all threads are in use, the new task will be queued 
     executor.submit(new runnableInheritedClass(results)); 
    } 
관련 문제