Call a function without waiting for it

前端 未结 6 1595
粉色の甜心
粉色の甜心 2021-02-02 00:59

Hi I was wondering if there was a way of calling a function/method (preferably in Python or Java) and continue execution without waiting for it.

Example:



        
6条回答
  •  滥情空心
    2021-02-02 01:46

    You'd better start with an ExecutorService instead of going directly with raw threads. It provides pooling, completion detection, and there are subclasses which also have some scheduling. For instance:

    ...
    // Create a simple instance with a single thread in the pool
    ExecutorService executor = Executors.newFixedThreadPool(1); 
    ...
    Future future = executor.submit(new Callable() {
        @Override
        public Integer call() {
            return YourFunction();
        }
    });
    ...
    
    // To wait for YourFunction() to finish, and get the result:
    Integer result = future.get();
    

    You can submit as many asynchronous tasks to the ExecutorService as you like; they will be executed in parallel, or sequentially, depending on the implementation you choose, on the number of threads in the backing thread pool, etc.

提交回复
热议问题