1、Future represents the result of an asynchronous * computation. Methods are provided to check if the computation is * complete, to wait for its completion, and to retrieve the result of * the computation. The result can only be retrieved using method * get when the computation has completed, blocking
2、 if * necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to * determine if the task completed normally or was cancelled. Once a * computation has completed, the computation cannot be cancelled. * If you would like to use a for the sake * of c
3、ancellability but not provide a usable result, you can * declare types of the form code Future and * return nullbSample Usage (Note that the following classes are all * made-up.) code * interface ArchiveSearcher String search(String target); * class App * ExecutorService executor = . * ArchiveSearch
4、er searcher = . * void showSearch(final String target) * throws InterruptedException * Future future * = executor.submit(new Callable() * public String call() * return searcher.search(target); * ); * displayOtherThings(); / do other things while searching * try * displayText(future.get(); / use futu
5、re * catch (ExecutionException ex) cleanup(); return; * * * The link FutureTask class is an implementation of that * implements Runnable, and so may be executed by an Executor. * For example, the above construction with submit could be replaced by: * FutureTask future = * new FutureTask(new Callable
6、 * executor.execute(future);Memory consistency effects: Actions taken by the asynchronous computation a href=package-summary.html#MemoryVisibility happen-before * actions following the corresponding code Future.get() in another thread. * see FutureTask * see Executor * since 1.5 * author Doug Lea *
7、param The result type returned by this Futures method public interface Future /* * Attempts to cancel execution of this task. This attempt will * fail if the task has already completed, has already been cancelled, * or could not be cancelled for some other reason. If successful, * and this task has
8、not started when is called, * this task should never run. If the task has already started, * then the mayInterruptIfRunning parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task. After this method returns, subsequent calls to link #isDon
9、e will * always return true. Subsequent calls to link #isCancelled * will always return if this method returned * param mayInterruptIfRunning if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete * return false if the task could not be canc
10、elled, * typically because it has already completed normally; otherwise boolean cancel(boolean mayInterruptIfRunning); * Returns if this task was cancelled before it completed * normally. boolean isCancelled(); if this task completed. * Completion may be due to normal termination, an exception, or *
11、 cancellation - in all of these cases, this method will return if this task completed boolean isDone(); * Waits if necessary for the computation to complete, and then * retrieves its result. * return the computed result * throws CancellationException if the computation was cancelled * throws Executi
12、onException if the computation threw an * exception * throws InterruptedException if the current thread was interrupted * while waiting V get() throws InterruptedException, ExecutionException; * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its r
13、esult, if available. * param timeout the maximum time to wait * param unit the time unit of the timeout argument * throws TimeoutException if the wait timed out V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; Callable返回Future示例import java.util.co
14、ncurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit; * Callable的Future用法 * package .CallableDemo * date 2017年4月5日 下午2:53:18 * author pengjunlin * comment * update public class Call
15、ableFuture * param args * throws Exception * throws InterruptedException public static void main(String args) throws InterruptedException, Exception / TODO Auto-generated method stub ExecutorService exec = Executors.newCachedThreadPool(); / Future是一个接口,该接口用来返回异步的结果。 Future st = exec.submit(new TaskC
16、allable(); /* 同步结果,并且设置超时时间 */ System.out.println(st.get(10000, TimeUnit.MILLISECONDS); System.out.println(finished);class TaskCallable implements Callable public String call() throws Exception Thread.sleep(1000); return callstatus=OK;FutureTaskFutureTask实现了java.util.concurrent.RunnableFuture接口,实际上实
17、现了Runnable和 Future两个接口。FutureTask源码import java.util.concurrent.locks.LockSupport; * A cancellable asynchronous computation. This class provides a base * implementation of link Future, with methods to start and cancel * a computation, query to see if the computation is complete, and * retrieve the re
18、sult of the computation. The result can only be * retrieved when the computation has completed; the code get * methods will block if the computation has not yet completed. Once * the computation has completed, the computation cannot be restarted * or cancelled (unless the computation is invoked usin
19、g * link #runAndReset). A code FutureTask can be used to wrap a link Callable or * link Runnable object. Because code FutureTask implements * code Runnable, a code FutureTask can be submitted to an * link Executor for execution. In addition to serving as a standalone class, this class provides * cod
20、e protected functionality that may be useful when creating * customized task classes. The result type returned by this FutureTasks code get methods public class FutureTask implements RunnableFuture /* * Revision notes: This differs from previous versions of this * class that relied on AbstractQueued
21、Synchronizer, mainly to * avoid surprising users about retaining interrupt status during * cancellation races. Sync control in the current design relies * on a state field updated via CAS to track completion, along * with a simple Treiber stack to hold waiting threads. * Style note: As usual, we byp
22、ass overhead of using * AtomicXFieldUpdaters and instead directly use Unsafe intrinsics. * The run state of this task, initially NEW. The run state * transitions to a terminal state only in methods set, * setException, and cancel. During completion, state may take on * transient values of COMPLETING (while outcome is being set) or * INTERRUPTING (only while interrupting the runner to satisfy a * cancel(true). Transitions from these intermediate to final * states use cheaper ordered/lazy writes because values are uniq
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1