2016-08-02 1 views
2

는 실행자에 인 newFixedThreadPool에 관한 문서에 따르면, 나는 인해 다음 작업을 실행하는 데 필요한 경우, 새가 그 자리를 취할 것입니다 종료 이전에 실행 중에 실패에ExcecutorService는 실행 중에 언제 실패합니까?

어떤 스레드가 종료되면 발견했다. 내 코드를 실행하는 동안 시간이 ExecutorService를이 스레드 중 하나가 실패를 결정 않는 경우

pool-1-thread-5 or less 그래서 궁금 할 생각 pool-1-thread-3212 같이 간다

, 나는 용량 5 개 킵 생성 스레드 내 고정 크기의 스레드를 감지 새로운 것을 시작하십시오.

아무도 내게 왜 이런 일이 일어나는 이유를 안내해 줄 수 있습니까?

답변

2

예외 처리를 제대로 구현하지 않은 경우 ExeuctorService에 작업을 제출하는 방식에 따라 스레드가 중단됩니다.

FixedThreadPool을 사용하고 있기 때문에 고정 된 수의 스레드가 스레드가 없어지면 유지해야합니다.

submit 대신 execute을 사용하면 처리되지 않은 예외가 발생할 경우 스레드가 죽습니다.

샘플 코드는 execute()

수입하고있는 java.util.concurrent를 사용하여 예외 & 스레드 죽음을 시뮬레이션. *;

import java.util.*; 

public class ThreadDeath{ 
    public ThreadDeath() 
    { 
     System.out.println("creating service"); 
     ExecutorService service = Executors.newFixedThreadPool(2); 
     for (int i=0; i < 5; i++){ 
      service.execute(new Runnable(){ 
        public void run(){ 
         int a=4, b = 0; 
         System.out.println("Thread Name before divide by zero:"+Thread.currentThread().getName()); 
         System.out.println("a and b="+a+":"+b); 
         System.out.println("a/b:"+(a/b)); 

        } 
       }); 
     } 
     service.shutdown(); 
    } 
    public static void main(String args[]){ 
     ThreadDeath test = new ThreadDeath(); 
    } 
} 

이제 출력 스레드 이름을 확인하십시오

creating service 
Thread Name before divide by zero:pool-1-thread-1 
Thread Name before divide by zero:pool-1-thread-2 
a and b=4:0 
a and b=4:0 
Exception in thread "pool-1-thread-1" Thread Name before divide by zero:pool-1-thread-3Exception in thread "pool-1-thread-2" 
a and b=4:0 
Thread Name before divide by zero:pool-1-thread-4 
Exception in thread "pool-1-thread-3" a and b=4:0java.lang.ArithmeticException:/by zero 

Thread Name before divide by zero:pool-1-thread-5 

지금 바로 submitexecute를 교체 Runnable 작업을 제출하면서. 예외는 삼켜 출력이 같다됩니다

private boolean addWorker(Runnable firstTask, boolean core) 
grepcode 링크를 참조, 스레드 생성에 대한 자세한 내용은

creating service 
Thread Name before divide by zero:pool-1-thread-1 
a and b=4:0 
Thread Name before divide by zero:pool-1-thread-2 
a and b=4:0 
Thread Name before divide by zero:pool-1-thread-1 
a and b=4:0 
Thread Name before divide by zero:pool-1-thread-2 
Thread Name before divide by zero:pool-1-thread-1 
a and b=4:0 
a and b=4:0 

(FixedThreadPool 크기가 2이기 때문에 당신은 두 개의 스레드를 볼 수 있습니다)

+0

질문이 없으므로 답을 찾아야합니다. 청결하고 완벽한 팁이 필요합니다. – BinaryProbe

+0

submit() 메서드를 사용하여 예외를 잡기 위해 관련 SE 질문을 확인할 수 있습니다. http://stackoverflow.com/questions/3929342/choose-between-executorservices-submit-and-executorservices-execute/35424481#35424481 –

관련 문제