FutureTask如何进行异步计算 [英] How FutureTask is asynchronous computation

查看:314
本文介绍了FutureTask如何进行异步计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

new Thread(new Runnable() {
           public void run() {
                 .............
                 .............
                 .............
    }
}).start();

如果我主要执行此操作,它将创建一个新线程并向其提交任务以进行异步计算.

If i will do this in main it will create a new thread and will submit a task to it for asynchronous calculation.

如果您看到FutureTask 文档,它还会显示:

If you see FutureTask documentation it also says:

可取消的异步计算.此类提供了基础 未来的实现,带有启动和取消的方法 计算,查询以查看计算是否完成,然后检索 计算结果.

A cancellable asynchronous computation. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation.

那么FutureTask asynchronous computation 的方式是如何在内部创建线程并提交实例化FutureTask时我们给它的任务,例如:

So how FutureTask is an asynchronous computation does it create thread internally and submit the task that we give it at the time of instantiating FutureTask like:

FutureTask f = new FutureTask(new MyCallable());

否则,它不能是异步计算,请向我提供FutureTask

Otherwise it can't be an asynchronous computation , please provide me the code snippet from the FutureTask source code where it submits the task to thread, to make it asynchronous computation. Thanks.

我得到了答案.基本上,这是试图在与调用方相同的线程中运行任务.在给定的代码中很明显:

I got the answer. It's is basically trying to run the task in the same thread as that of caller. It is pretty evident in the given code:

当您调用futureTask.run()时,它仅调用sync.innerRun();,而sync是内部类Sync的实例.因为它只在同一线程中调用可调用对象上的call().

When you call futureTask.run() it just calls sync.innerRun(); and sync is the instance of inner class Sync. In that it just calls call() on the callable object in the same thread.

void innerRun() {
        if (!compareAndSetState(READY, RUNNING))
            return;

        runner = Thread.currentThread(); //here it is getting the current thread
        if (getState() == RUNNING) { 
            V result;
            try {
                result = callable.call();//here calling call which executes in the caller thread.
            } catch (Throwable ex) {
                setException(ex);
                return;
            }
            set(result);
        } else {
            releaseShared(0); // cancel
        }
    }

推荐答案

因此,FutureTask如何进行异步计算,是否会在内部创建线程并提交实例化FutureTask时提供的任务,例如:

So how FutureTask is an asynchronous computation does it create thread internally and submit the task that we give it at the time of instantiating FutureTask like:

FutureTask并非旨在供用户直接使用.它旨在通过ExecutorService接口和实现它的类来使用.就是那些使用FutureTask并派生线程的类,等等.您可能需要阅读有关

FutureTask is not designed to be used directly by the user. It is designed to be used through the ExecutorService interface and the classes that implement it. It is those classes that use FutureTask and fork the threads, etc.. You may need to read more information about how to use the ExecutorService concurrency classes.

ThreadPoolExecutor类是实际管理池中线程的主要类.通常,您调用Executors.newCachedThreadPool()Executors.newFixedThreadPool(10)以获得它的实例.

The ThreadPoolExecutor class is the main one that actually does the management of the threads in the pool. Typically you call Executors.newCachedThreadPool() or Executors.newFixedThreadPool(10) to get an instance of it.

// create a thread pool with 10 workers
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// define your jobs somehow
for (MyCallable job : jobsToDo) {
    // under the covers this creates a FutureTask instance
    Future future = threadPool.submit(job);
    // save the future if necessary in a collection or something
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
// now we can go back and call `future.get()` to get the results from our jobs

从学术的角度来看,TPE是在AbstractExecutorService之下扩展的,您可以在其中看到FutureTask类用于管理线程池中的任务:

From an academic standpoint, under the covers TPE extends AbstractExecutorService and it is there that you can see the FutureTask class being used to manage the tasks in the thread-pool:

public <T> Future<T> submit(Callable<T> task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<T> ftask = newTaskFor(task);
    execute(ftask);
    return ftask;
}
...
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
    return new FutureTask<T>(callable);
}

TPE内部的代码非常复杂,要显示执行异步调用的代码段"并不容易. TPE会查看是否需要向池中添加更多线程.将其提交到可以拒绝它或接受它的任务队列,然后线程使任务出队并在后台运行它们.

The code inside of TPE is pretty complicated and it's not easy to show a "snippet" that performs the asynchronous calls. The TPE sees if it needs to add more threads to the pool. submits it to a task queue which can either reject it or accept it, and then the threads dequeue the task and run them in the background.

这篇关于FutureTask如何进行异步计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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