简体   繁体   English

FutureTask如何进行异步计算

[英]How FutureTask is asynchronous computation

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. 如果我将在main中执行此操作,它将创建一个新线程并将向其提交任务以进行异步计算。

If you see FutureTask documentation it also says: 如果您看到FutureTask 文档,它还会说:

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. 此类提供Future的基本实现,包括启动和取消计算的方法,查询计算是否完成的查询,以及检索计算结果。

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是一个asynchronous computation如何在内部创建线程并提交我们在实例化FutureTask时提供的任务,如:

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

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. 否则它不能是异步计算,请提供FutureTask 源代码中的代码片段,它将任务提交给线程,以使其进行异步计算。 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: 在给定的代码中非常明显:

When you call futureTask.run() it just calls sync.innerRun(); 当你调用futureTask.run()它只调用sync.innerRun(); and sync is the instance of inner class Sync . sync是内部类Sync的实例。 In that it just calls call() on the callable object in the same thread. 因为它只是在同一个线程中的可调用对象上调用call()

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
        }
    }

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是一个异步计算如何在内部创建线程并提交我们在实例化FutureTask时提供的任务,如:

FutureTask is not designed to be used directly by the user. FutureTask不是为用户直接使用而设计的。 It is designed to be used through the ExecutorService interface and the classes that implement it. 它旨在通过ExecutorService接口和实现它的类来使用。 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 . 这些类使用FutureTask并分叉线程等。您可能需要阅读有关如何使用ExecutorService并发类的更多信息。

The ThreadPoolExecutor class is the main one that actually does the management of the threads in the pool. ThreadPoolExecutor类是实际管理ThreadPoolExecutor的主要类。 Typically you call Executors.newCachedThreadPool() or Executors.newFixedThreadPool(10) to get an instance of it. 通常,您调用Executors.newCachedThreadPool()Executors.newFixedThreadPool(10)来获取它的实例。

// 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

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: 从学术角度来看,TPE扩展了AbstractExecutorService ,你可以看到FutureTask类用于管理线程池中的任务:

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

The code inside of TPE is pretty complicated and it's not easy to show a "snippet" that performs the asynchronous calls. TPE中的代码非常复杂,并且显示执行异步调用的“代码段”并不容易。 The TPE sees if it needs to add more threads to the pool. TPE会查看是否需要向池中添加更多线程。 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. 将其提交给任务队列,该队列可以拒绝它或接受它,然后线程将任务队列化并在后台运行它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM