【问题标题】:Callable interface with executor framework. Why Program didn't exit even after returning from call method带有执行器框架的可调用接口。为什么程序即使从调用方法返回后也没有退出
【发布时间】:2026-01-01 20:10:01
【问题描述】:

我正在尝试使用执行器框架来理解可调用接口。这是可行的,但我有点困惑,为什么即使从调用方法返回后程序也不会退出。

代码:

CallableExample.java

package callable1;

import java.util.concurrent.Callable;

public class CallableExample implements Callable<String> {

    @Override
    public String call() throws Exception {
        // TODO Auto-generated method stub
        String s = Thread.currentThread().getName();
        for(int i = 0 ; i < 10 ; i++)
        {
            s += ""+i;
            System.out.println(s);
            Thread.sleep(1000);
        }

        return s;
    }
}

Tester.java

package callable1;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Tester {

    public static void main(String[] args) throws Exception
    {
        ExecutorService pool = Executors.newFixedThreadPool(5);
        Future<String> ftask = pool.submit(new CallableExample());

        System.out.println("getting result");
        System.out.println("----" + ftask.get());
        System.out.println("main over");
    }
}

【问题讨论】:

  • 这是线程池的设计和实现。您需要在您的执行人上致电shutdown()。您可以在 javadocs 中阅读更多内容。另见shutdownNow()
  • 非常感谢@VladimirVagaytsev。好用,我忘记关机了。
  • 不客气 :) 如果您喜欢,请随时接受答案 :)

标签: java multithreading threadpool executorservice callable


【解决方案1】:

java.util.concurrent.* 的线程池是以这种方式设计的,因此您必须在执行程序上调用 shutdown()shutdownNow()。否则程序不会停止。您可以在 javadocs 中找到方法之间的区别。

【讨论】:

    最近更新 更多