FutureTask如何进行异步计算

Try*_*ing 8 java multithreading asynchronous futuretask

new Thread(new Runnable() {
           public void run() {
                 .............
                 .............
                 .............
    }
}).start();
Run Code Online (Sandbox Code Playgroud)

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

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

可取消的异步计算.此类提供Future的基本实现,包括启动和取消计算的方法,查询计算是否完成的查询,以及检索计算结果.

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

FutureTask f = new FutureTask(new MyCallable());
Run Code Online (Sandbox Code Playgroud)

否则它不能是异步计算,请提供FutureTask 源代码 中的代码片段,它将任务提交给线程,以使其进行异步计算.谢谢.


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

当你调用futureTask.run()它时只调用它sync.innerRun();并且sync是内部类的实例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
        }
    }
Run Code Online (Sandbox Code Playgroud)

Gra*_*ray 7

那么FutureTask是一个异步计算如何在内部创建线程并提交我们在实例化FutureTask时提供的任务,如:

FutureTask不是为用户直接使用而设计的.它旨在通过ExecutorService接口和实现它的类来使用.正是这些类使用FutureTask和分叉线程等.您可能需要阅读有关如何使用ExecutorService并发类的更多信息.

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
Run Code Online (Sandbox Code Playgroud)

从学术角度来看,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);
}
Run Code Online (Sandbox Code Playgroud)

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