2015-02-02 2 views
2

자바로 타이머 테스트 중입니다.자바 타이머에 관하여

내 프로그램은 타이머를 시작한 다음 2 초 동안 기다리고 타이머를 취소하고 j 변수를 인쇄합니다.

그러나 타이머를 취소하더라도 여전히 실행됩니다. 감사.

public static Timer time; 
public static int j=0; 

    public static void main(String[] args) 
    { 
     try { 
      testrun(); 
      Thread.sleep(2000); 
      time.cancel(); 
      System.out.println("timer stop"); 

      System.out.println(j); 

     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 

    public static void testrun() 
    { 
     time = new Timer(); 
     time.schedule(new TimerTask() { 
       @Override 
       public void run() { 
        for(int i = 0;i<100;i++){ 
        System.out.println(i); 
        j++; 
        } 

        System.out.println("End timer"); 
       } 
      }, 1000, 1000); 
    } 
+0

가능한 복제본 [Java - Timer.cancel() v/s TimerTask.cancel()] (http://stackoverflow.com/questions/21492693/java-timer-cancel-v-s-timertask-cancel) –

답변

2

cancel 때문에 단지 타이머를 중단 - 작업이 완료로 실행됩니다 시작합니다.

작업을 중단하려면 작업을 추적하고 interrupt 메서드를 호출해야합니다.

public static Timer time = new Timer(); 
public static Thread runningThread = null; 
public static int j = 0; 

public static void main(String[] args) { 
    try { 
     testrun(); 
     Thread.sleep(2000); 
     time.cancel(); 
     System.out.println("timer stop"); 
     if (runningThread != null) { 
      // Interrupt the thread. 
      runningThread.interrupt(); 
     } 
     System.out.println(j); 

    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

public static void testrun() { 
    time.schedule(new TimerTask() { 
     @Override 
     public void run() { 
      // Catch the thread that is running my task. 
      runningThread = Thread.currentThread(); 
      for (int i = 0; i < 100; i++) { 
       System.out.println(i); 
       j++; 
      } 

      System.out.println("End timer"); 
     } 
    }, 1000, 1000); 
} 
1

Timer.cancel()에 대한 호출은 실행되는 것을 더 이상 계획하지만 실행되지 않은 작업을 중지하지만, 실행중인 작업을 중단하지 않습니다.

Javadoc for Timer.cancel() (강조 광산)를 참조하십시오 :

은 현재 예약 된 모든 작업을 삭제이 타이머를 종료합니다. 현재 실행중인 작업 (있는 경우)과 간섭하지 않습니다.