2012-10-18 2 views
1

이 질문은 그것에 이르는 몇 가지 질문의 절정입니다. 나는 내가 한 모든 변화를 저지르기 전에 모든 것을 바로 잡고 싶습니다.run()의 구현에 스레드 인터럽트 추가

public void doRun(){ 
    doChildClassStuff(); 
} 
: 내 추상 클래스를 구현하는 하위 클래스에 다음

public abstract void doRun(); 

public void run(){ 
    try{ 
    while(!Thread.currentThread().isInterrupted() || hasRunBefore){ 
     doRun(); 
    } 
    }catch (InterruptedException e){Thread.sleep(1); System.out.println("Thread Interrupted: "); e.printStackTrace(); } 

} 

: 추상 클래스에서

: 그래서 여기

내가 데이터 구조를 위해 함께 일하고 있어요 무엇

다음 주 수업에서 이것을 호출 할 때 나는 간단히

ClassName myClass = new ClassName(constructor.list); 
ExecutorService threadPool = Executors.newFixedThreadPool(12); 
    List<Future<?>> taskList = new ArrayList<Future<?>>(); 
    taskList.add(myClass); 
    for(Future future : taskList){ 
     try{ 
      future.get(1, TimeUnit.SECONDS); 
     }catch(CancellationException cx){ System.err.println("Cancellation Exception: "); cx.printStackTrace(); 
     }catch(ExecutionException ex){ System.err.println("Execution Exception: ");ex.printStackTrace(); 
     }catch(InterruptedException ix){ System.err.println("Interrupted Exception: ");ix.printStackTrace(); 
     }catch(TimeoutException ex) {future.cancel(true);} 
    } 
    threadPool.shutdown(); 
    threadPool.awaitTermination(60, TimeUnit.SECONDS); 
    threadPool.shutdownNow(); 

thread.sleep()이 실패하면 해당 스레드가 중단되어 종료되어야 함을 의미합니다. 모든 스레드가 60 초 이상 걸리면 모두 awaitTermination의 thread.interrupt() 명령이 전송됩니다.

여기에서 완전히 벗어 났습니까?

답변

1

기본 클래스에서 스레드 인터럽트를 처리하는 것처럼 보입니다. 아쉽게도 기본 클래스가 스레드 인터럽트를 "수신 대기"할 수있는 방법은 없습니다. doChildClassStuff()Thread.currentThread().isInterrupted() 자체 검사를 처리해야합니다. 쓰래드가 인터럽트 되었는지를 감지 할 수 있어야합니다. 그러면 쓰레드는 돌아가거나 InterruptedException을 던질 수 있습니다.

Thread.sleep(1);은 필요하지 않습니다. 스레드가 인터럽트 된 경우 InterruptedException이 표시되지만 Thread.currentThread().isInterrupted()으로 쉽게 테스트 할 수 있습니다. 이미 InterruptedException에 대한 catch 블록에 있기 때문에 어쨌든 요점은 무엇인지 정확히 알지 못합니다. 또한 doRun()은 코드 샘플 (그대로)이 컴파일되지 않도록 InterruptedException을 던지지 않습니다.

+0

부모에게 리스너를 구현할 수있는 방법이 있습니까? 제가 손으로 수정해야 할 약 50 개의 클래스가 있습니다. 이것은 커밋 한 TON을 의미합니다. –

+0

불행하게도, @ Damien.Bell은 없습니다. 기본 클래스가 스레드 인터럽트를 "수신 대기"할 수있는 방법은 없습니다. – Gray

+0

젠틀, 물론 ... 이것은 또한 내 자식 클래스에서 또 다른 문제를 제시하며, 루프에서 실행되도록 만들어지지 않았으며, 각각 몇 개의 실행 가능한 메서드를 각각 실행하는 본질적으로 간단한 문입니다. –

관련 문제