代码之家  ›  专栏  ›  技术社区  ›  ealeon

我的程序没有返回/以Executor结束

  •  2
  • ealeon  · 技术社区  · 6 年前

     import java.util.concurrent.*;
    
     public class SquareCalculator {
         private ExecutorService executor = Executors.newSingleThreadExecutor();
    
         public Future<Integer> calculate(Integer input) {
             return executor.submit( () -> {
                 Thread.sleep(1000);
                 return input * input;
             });
         }
    
         public static void main(String[] args) {
             try {
                 Future<Integer> future = new SquareCalculator().calculate(10);
                 while (!future.isDone()){
                     System.out.println("Calculating...");
                     Thread.sleep(300);
                 }
    
                 Integer result = future.get();
                 System.out.println("we got: " + result);
             } catch(InterruptedException | ExecutionException e) {
                 System.out.println("had exception");
             }
         }
     }
    

    它产生:

    java SquareCalculator
    Calculating...
    Calculating...
    Calculating...
    Calculating...
    we got: 100
    

    但应用程序永远不会终止。

    3 回复  |  直到 6 年前
        1
  •  3
  •   Shesh Nath Mishra    6 年前

    应该发表评论,但没有足够的声誉。

    您应该在executor上调用shutdown。您可以从以下链接获取更多详细信息: Reason for calling shutdown() on ExecutorService

        2
  •  3
  •   automatictester    6 年前

       finally {
            if (executor != null) {
                executor.shutdown();
            }
        }
    
        3
  •  2
  •   VHS    6 年前

    您需要在程序结束时关闭executor framework,并等待它正常终止。。

    executor.shutdown();
    try {
        executor.awaitTermination(4 * 3600, TimeUnit.SECONDS);
    } catch (Exception e) {
        e.printStackTrace();
    }