Callable中的线程保持等待状态。如何杀死线程?

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

有很多类似的问题,但没有解决方案对我有用。

我有一个Callable,它需要运行一定的时间。在执行Call方法期间,它必须在while条件中定期进行一些检查,以检查是否必须继续运行。我还希望能够从外部停止可调用对象(API调用)。

下面的代码是简化版本,但有相同的问题:

当可调用对象返回时,线程保持在等待状态。如何杀死该线程?

public class MyCallable implements Callable<Foo> {
    private AtomicBoolean stop = new AtomicBoolean(false);

    @Override
    public Foo call() {
        System.out.printf("New thread with ID=%d\n",
                Thread.currentThread().getId());
        Foo foo = new Foo();

        while (!stop.get()) {
            try {
                Thread.sleep(1000); // Sleep for some time before doing checks again
            } catch (InterruptedException e) {
            }
        }

        System.out.printf("State before returning foo: %s\n",
                Thread.currentThread().getState());
        return foo;
    }

    public void stop() {
        this.stop.set(true);
    }
}
public class Main {
    public static void main(String[] args) throws InterruptedException {
        MyCallable myCallable = new MyCallable();
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        Future<Foo> future = executorService.submit(myCallable);

        printThreads();

        System.out.println("Calling stop\n");
        myCallable.stop();

        while (!future.isDone()) {
            Thread.sleep(200);
        }

        System.out.println("After future is done: ");
        printThreads();
    }

    // Helper method
    private static void printThreads() {
        List<Thread> threads = Thread.getAllStackTraces().keySet()
                .stream()
                .filter(t -> t.getName().contains("pool"))
                .collect(Collectors.toList());

        threads.forEach(t -> System.out.printf("ID=%s STATE=%s\t\n", t.getId(), t.getState()));
        System.out.println();
    }
}

这是程序的输出

Output

java multithreading callable
1个回答
0
投票

您无需手动终止由ExecutorService管理的线程。您需要正常关闭服务,它将终止其线程。

executorService.shutdown();

通常,完成单个任务后,线程工作者不会被终止。将其移至WAITING状态,直到出现新任务为止。这些东西由ExecutorService管理。关闭它会导致终止它负责的线程。

© www.soinside.com 2019 - 2024. All rights reserved.