java - FutureTask 是如何进行异步计算的

标签 java multithreading asynchronous futuretask

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

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

如果您看到 FutureTask documentation它还说:

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

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

否则不可能是异步计算,请提供FutureTask中的代码片段source code它将任务提交给线程,使其成为异步计算。谢谢。


我得到了答案。它基本上是尝试在与调用者相同的线程中运行任务。这在给定的代码中非常明显:

当您调用 futureTask.run() 时,它只会调用 sync.innerRun();sync 是内部类 同步。因为它只是在同一线程中对可调用对象调用 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 并非设计为供用户直接使用。它旨在通过 ExecutorService 接口(interface)和实现它的类来使用。它是那些使用 FutureTask 和 fork 线程等的类。您可能需要阅读有关 how to use the ExecutorService concurrency classes 的更多信息。 .

ThreadPoolExecutor 类是真正管理池中线程的主要类。通常,您调用 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

从学术的角度来看,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);
}

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

关于java - FutureTask 是如何进行异步计算的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19768540/

相关文章:

java - 使用方法中声明的相同方法?

java - 我想根据表单中输入的数字更改屏幕转换目标

java - Maven - 无法执行 JAR

java - 使用路标签署 HTTP 消息时获取 401

java - 每个线程一个数据库连接?

java - java.util.concurrent.Executor 是如何工作的?

android - 如何每 2 秒在两个值之间连续切换文本切换器

php - 复杂项目的Ajax加载

javascript - Node.js 中的异步 http.get 调用(Learyounode 练习)

asynchronous - 如何实现轮询异步 fn 的 Future 或 Stream?