Executor 동작 주기

자바 병렬 프로그래밍 - 1.4 스레드는 어디에나, 39p.

Java 어플리케이션을 실행하면 Timer 라는 스레드가 생성되어 있는 것을 알 수 있다.

Timer 클래스 등을 사용하여 실행되는 명령의 주체는 main 스레드가 아니라 Timer 스레드임을 주의해야한다. (이는 AWT 등의 GUI 스레드도 마찬가지)

다음과 같은 코드를 실행하면 실행스레드가 Timer-0 로 나온다.

public class TimerTaskExam {
 
    public static void main(String args[]) throws InterruptedException {
        Timer timer = new Timer();
        CountDownLatch countDownLatch = new CountDownLatch(5);
         
        AtomicInteger atomicInteger = new AtomicInteger(0);
         
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                countDownLatch.countDown();
                System.out.println(atomicInteger.incrementAndGet());
                System.out.println(Thread.currentThread().getName());
            }
        }, 0, 1L);
         
        System.out.println("AWAIT...");
        countDownLatch.await();
        System.out.println("END.");
        timer.cancel();
    }
     
}

실행결과

AWAIT...
1
Timer-0
2
Timer-0
3
Timer-0
4
Timer-0
5
Timer-0
END.