线程中断不停止执行无限任务

问题描述 投票:0回答:1

我有以下代码片段:

@Async("executor")
    public CompletableFuture<List<SecondObject>> getSecondObject(List<FirstObject> firstObject) {

        CompletableFuture<List<SecondObject>> future = new CompletableFuture<>();
        final int timeout = 5000;
        Timer timer = new Timer();

        //Thread created by configuration
        final Thread executorThread = Thread.currentThread();

        //Method responsible for thread interruption
        final TimerTask interruptTask = new TimerTask() {
            @Override
            public void run() {

                Thread timerTaskThread = Thread.currentThread();
                System.out.println("Exception for thread "+executorThread.getName()+" is thrown");
                System.out.println("Timer task thread "+timerTaskThread.getName()+" is issued");
                executorThread.interrupt();
                future.completeExceptionally(new InterruptedException());
            }
        };
        //Schedule set for thread interruption
        timer.schedule(interruptTask, timeout);
        System.out.println("Thread " + Thread.currentThread().getName() + " is created.");
        System.out.println("Thread " + Thread.currentThread().getName() + " is executing a task.");
        List<SecondObject> secondObject = Collections.emptyList();
        for (int i = 0; i < 5; i++) {
            i--;
        }
        future.complete(secondObject));
        timer.cancel();
        System.out.println("Thread " + Thread.currentThread().getName() + " has been terminated.");

        return future;
    }
}

和试图访问

CompletableFuture
的代码。

List<FirstObject> firstObject = Collections.emptyList();
List<SecondObject> testedList = null;
CompletableFuture<List<SecondObject>> future = sectionsService.getSecondObject(firstObject);
            try {
                testedList = future.get();
            } catch (InterruptedException | ExecutionException e) {

            }

我遇到的问题是,当我调用

get()
方法时,尽管每个
TimerTask
都跟踪用
@Async
创建的每个新线程的超时,无限任务(这里是无限的
for loop
)完全阻塞主线程.
@Async
线程的中断标志被抛出,但线程本身并未停止 - 尽管线程被中断,程序仍无限执行
for loop
。程序一直等到
get()
返回一些东西。我需要
TimerTask
在超过超时时实际停止线程。

java multithreading spring-boot completable-future timertask
1个回答
0
投票
future.get(long timeout, TimeUnit unit);
© www.soinside.com 2019 - 2024. All rights reserved.