4. Two-Phase Termination Code Public final void run(){ try { while ( !isShutdownRequested() ) { doWork(); } } catch (InterruptedException e) { } finally { doShutdown(); } 종료요구가 있었는가 ‘try...finally 사용’ 작업 처리 종료 처리
5. public class CountupThread extends Thread { private long counter = 0; private volatile boolean shutdownRequested = false; public void shutdownRequest() { shutdownRequested = true; interrupt(); } public boolean isShutdownRequested() { return shutdownRequested; } public final void run(){ try { while ( !isShutdownRequested() ) { doWork(); } } catch (InterruptedException e) { } finally { doShutdown(); } private void doWork() throws InterruptedException { counter++; System.out.println(“doWork: counter =“+counter); Thread.sleep(500); } private void doShutdown() { System.out.println(“doShutDown”); } 예제소스 public class Main { public static void main(String[] args) { System.out.println(“main:BEGIN”); try { CountupThread t = new CountupThread(); t.start(); Thread.sleep(10000); t.shutdownRequest(); t.join(); } catch (InterruptedException e) { e.printStackTrace(); } }
9. 보강 1. 쓰레드의 Interrupt 상태 Interrupt() 함수를 호출하면 대상 쓰레드는 항상 InterruptedException 을 통보하는게 아님. 2. concurrent 패키지 Java.util.concurrent.CountDownLatch -> 10개의 일이 모두 끝나기를 기다린다. Java.util.concurrent.CyclicBarrier -> 3개의 쓰레드모두 N 단계를 종료할때까지 어떤 쓰레드도 N단계+1 로 나아가지 않는다. 3. Volatile synchronized 는 배타제어와 동기화. Volatile 은 동기화만 이루어짐. volatile 필드에 입력한 내용은 다른 쓰레드가 곧바로 볼수있음. reorder 가 일어나지 않음.
10. 정리 종료하기전에 특정 종료처리를 실행. 종료요구 flag 를 이용하여 주기적으로 종료요청 여부판단 실행시 예외가 발생하더라도 확실하게 종료 처리를 시키기 위해서 try...finally 사용