将来的任务完成后

将来的任务完成后

本文介绍了将来的任务完成后,Java Process没有退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我使用Future的代码段.

This is my code snippet using Future.

import java.util.concurrent.*;
import java.util.*;

public class FutureDemo{

    public FutureDemo(){

            /* Future */
            ExecutorService service = Executors.newFixedThreadPool(2);
            for ( int i=0; i<10; i++){
                    MyCallable myCallable = new MyCallable((long)i);
                    Future<Long> futureResult = service.submit(myCallable);
                    Long result = null;
                    try{
                            result = futureResult.get(5000, TimeUnit.MILLISECONDS);
                    }catch(TimeoutException e){
                            System.out.println("Time out after 5 seconds");
                            futureResult.cancel(true);
                    }catch(InterruptedException ie){
                            System.out.println("Error: Interrupted");
                    }catch(ExecutionException ee){
                            System.out.println("Error: Execution interrupted");
                    }
                    System.out.println("Result:"+result);
            }
    }

    public static void main(String args[]){
            FutureDemo fc = new FutureDemo();
    }

    class MyCallable implements Callable{
            Long id = 0L;

            public MyCallable(Long val){
                    this.id = val;
            }

            public Long call(){
                    return id;
            }
    }
}

输出:

D:\Study\Java>java FutureDemo
Result:0
Result:1
Result:2
Result:3
Result:4
Result:5
Result:6
Result:7
Result:8
Result:9
-

提交所有Future任务后,我得到了结果,但是程序仍然没有退出.我的光标闪烁,直到单击 CTRL + C ,Java进程才退出.有什么问题吗?

After submitting all Future tasks, I got the result but still the program did not quit. My cursor is blinking and java process did not quit till I click CTRL+C. What is the issue?

编辑:我无法关闭执行程序服务,除非通过服务器关闭触发了关闭挂钩.

EDIT: I can't shut down the executor service unless shut down hook is triggered with server shut down.

推荐答案

您需要调用service.shutdown()告诉ExecutorService不要等待任何其他任务.

You need to call service.shutdown() to tell the ExecutorService not to wait for any more tasks.

这篇关于将来的任务完成后,Java Process没有退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:51