Submitting FutureTasks to an Executor - why does i

2019-06-25 12:25发布

问题:

I have the following test code.

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

class  MyTask extends FutureTask<String>{
    @Override
    protected void done() {
        System.out.println("Done");
    }

    public MyTask(Runnable runnable) {
        super(runnable,null);
    }
}

public class FutureTaskTest {

    public static void main(String[] args)  {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        FutureTask<String> future = new MyTask(new Runnable() {
            public void run() {
                System.out.println("Running");
            }
        });

        executor.submit(future);

        try {
            future.get();
        } catch (Exception ex ) {
            ex.printStackTrace();
        }
        executor.shutdownNow();

    }
}

This works fine - the overridden 'done' methond in MyTask is called when the task is done. But how does the executor know how to call that ?

The executor only have these submit methods:

public <T> Future<T> submit(Callable<T> task);
public Future<?> submit(Runnable task);

Internally it seems 'submit' wraps the callable/runnable in a new FutureTask(). As far as the executor is concerned I've submitted a Runnable or Callable - from what I gather from these 2 signatures. How does it know I submitted a FutureTask and know how to call my overridden done() ?

回答1:

From the executor's point of view, you've submitted a Runnable task. The run method of this task (implemented by FutureTask) is what calls done at the appropriate time. The executor doesn't make any direct call to done.



回答2:

The executor doesn't call done(). done() gets called by FutureTask when the call to run() is complete.



标签: java oop