문제

아래 코드에서, 의도 한대로 100 초 후에 타임 아웃 렉션을 포착하고 있습니다. 이 시점에서 나는 코드가 메인과 프로그램에서 종료 될 것으로 예상하지만 콘솔에 계속 인쇄합니다. 타임 아웃 후 실행을 중단하는 작업을 어떻게 얻습니까?

private static final ExecutorService THREAD_POOL = Executors.newCachedThreadPool();

private static <T> T timedCall(Callable<T> c, long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
    FutureTask<T> task = new FutureTask<T>(c);
    THREAD_POOL.execute(task);
    return task.get(timeout, timeUnit);
}


public static void main(String[] args) {

    try {
        int returnCode = timedCall(new Callable<Integer>() {
            public Integer call() throws Exception {
                for (int i=0; i < 1000000; i++) {
                    System.out.println(new java.util.Date());
                    Thread.sleep(1000);
                }
                return 0;
            }
        }, 100, TimeUnit.SECONDS);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }


}
도움이 되었습니까?

해결책

타임 아웃에서 작업을 취소하고 스레드를 방해해야합니다. 그게 뭐야 cancel(true) 방법은 용입니다. :

private static final ExecutorService THREAD_POOL = Executors.newCachedThreadPool();

private static <T> T timedCall(FutureTask<T> task, long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
    THREAD_POOL.execute(task);
    return task.get(timeout, timeUnit);
}


public static void main(String[] args) {
        try {
            FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
                public Integer call() throws Exception {
                        for (int i=0; i < 1000000; i++) {
                                if (Thread.interrupted()) return 1;
                                System.out.println(new java.util.Date());
                                Thread.sleep(1000);
                        }
                        return 0;
                }
            });
            int returnCode = timedCall(task, 100, TimeUnit.SECONDS);
        } catch (Exception e) {
                e.printStackTrace();
                task.cancel(true);
        }
        return;
}

다른 팁

필요할 때 신속하게 멈출 수 있어야합니다.

코드 :

public Integer call() throws Exception {
    for (int i=0; i < 1000000 && !task.cancelled(); i++) {
        System.out.println(new java.util.Date());
        Thread.sleep(1000); // throws InterruptedException when thread is interrupted
    }
    return 0;
}

전화 덕분에 이미 그렇게 할 수 있습니다 Thread.sleep(). 포인트입니다 futureTask.cancel(true) 다른 스레드를 방해하고 코드 가이 중단에 반응해야합니다. Thread.sleep() 것을 수행. 사용하지 않은 경우 Thread.sleep() 또는 기타 인터럽 가능한 차단 코드는 확인해야합니다. Thread.currentThread().isInterrupted() 혼자서, 가능한 한 빨리 그만두십시오 (예 : 던지기 new InterruptedException()) 이것이 사실이라고 생각할 때.

전화해야합니다 futureTask.cancel(true); 예외 핸들러에서 작업을 실행하는 스레드를 취소하고 인터럽트합니다.

내 조언은 중단 메커니즘에 대해 배우는 것입니다 (이것은 훌륭한 기사입니다. InterruptedException 처리), 그리고 그것을 사용하십시오.

TimeOutException을 잡으면 작업의 취소 (True) 메소드를 호출해야합니다 ...

또는 shutdownnow ()를 호출하여 ExecutorService를 종료하십시오 ...

또는 System.Exit (0)를 호출하여 VM을 종료하십시오.

귀하의 필요에 따라

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top