向执行者提交FutureTasks-为什么有效? [英] Submitting FutureTasks to an Executor - why does it work?

查看:52
本文介绍了向执行者提交FutureTasks-为什么有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下测试代码.

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();

    }
}

这很好用-完成任务后,将调用MyTask中重写的完成"方法. 但是执行者怎么知道该怎么称呼呢?

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);

在内部,似乎提交"将可调用/可运行包装在新的FutureTask()中. 就执行人而言,我已经提交了Runnable或Callable-从这两个签名中收集的信息. 它怎么知道我提交了FutureTask并知道如何调用覆盖的done()?

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() ?

推荐答案

从执行者的角度来看,您已经提交了Runnable任务.此任务的run方法(由实现)是在适当的时候调用done的方法.执行程序不会直接调用done.

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.

这篇关于向执行者提交FutureTasks-为什么有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆