java concurrent programming: Callable + Future + FutureTask Comments

 

Runnable
which should be our most familiar Runnable interface, it has only one run () function that will take a write operation in which the function has no return value. Then use a thread to execute the runnable you can achieve multi-threaded, Thread class calls the start () function is executed after a Runnable's run () function. Runnable the following statement: 

public interface Runnable {
/*
* @see java.lang.Thread#run()
*/
public abstract void run();
}

 


A Callable
a Callable and Runnable substantially similar functions, there is a Callable a call () function, but the call () function returns a value, and the Runnable run () function does not return the results to the client. Callable statement as follows:


public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}

 

Future
the Executor is Runnable and Callable scheduling container, Future is the result of execution for a particular task will be Runnable or Callable

Cancel the query is complete, get results, set the result of the operation. get method will block until the task returns the result (Future Introduction). Future the following statement:

 

public interface Future<V> {

/**
* 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 not started when <tt>cancel</tt> is called,
* this task should never run. If the task has already started,
* then the <tt>mayInterruptIfRunning</tt> parameter determines
* whether the thread executing this task should be interrupted in
* an attempt to stop the task.
*/
boolean cancel(boolean mayInterruptIfRunning);

/**
* Returns <tt>true</tt> if this task was cancelled before it completed
* normally.
*/
boolean isCancelled();

/**
* Returns <tt>true</tt> if this task completed.
*
*/
boolean isDone();

/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return the computed result
*/
V get() throws InterruptedException, ExecutionException;

/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the computed result
*/
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}

 


FutureTask
 

FutureTask is a RunnableFuture <V>

a FutureTask, class public <V> the implements RunnableFuture <V>
RunnableFuture Runnbale realized and achieved Futrue <V> these two interfaces

public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
另外FutureTaslk还可以包装Runnable和Callable<V>, 由构造函数注入依赖。

public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}

public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}

 

The above code block can be seen: Runnable injection is Executors.callable () function to Callable type, i.e. ultimately FutureTask Callable type of task execution. Implement the adaptation function is as follows:

public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}

 


RunnableAdapter adapter

 

/**
* A callable that runs given task and returns given result
*/
static final class RunnableAdapter<T> implements Callable<T> {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}

 


FutureTask achieve Runnable, Thread it through the implementation of the package,

FutureTask achieve Runnable, it can be submitted to the Executive ExcecuteService

Note: ExecuteService: create a thread pool instance of an object, which submit (Runnable), submit (Callable) method

 

Can () function to get directly get the results of the function blocks until results are returned.

So FutureTask Future is also Runnable, but also wraps the Callable (if it is Runnable will eventually be converted to Callable).

 

 

 

Callable and Future interfaces difference

The method is defined 1.Callable Call (), and the method is defined Runnable RUN (). 
Returns the value 2.Callable task execution, and the task is not Runnable return value.  
3.call () method can throw an exception, and the run () method is not throwing an exception. 
4. Run Callable task to get a Future object, Future represents the result of an asynchronous computation. 
5. It provides a method of checking computation is complete, to wait for the completion of calculation, and calculation of the search result. 
6. Future object can be understood by the task execution, the Executive cancel the task, but also get the results of task execution. 
7.Callable interface is similar to Runnable, Callable interface and implementation class implementation tasks are Runnable class that can be performed by other threads.

 

Example:

package com.xzf.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class RunnableFutureTask {
static ExecutorService executorService = Executors.newSingleThreadExecutor();    //创建一个单线程执行器
public static void main(String[] args) {
runnableDemo();    
futureDemo();
}
/**
* new Thread(Runnable arg0).start(); 用Thread()方法开启一个新线程
* runnable, 无返回值
*/
static void runnableDemo() {
new Thread(new Runnable() {    
public void run() {
System.out.println("runnable demo:" + fibc(20));    //有值
}

}).start();
}
/**
* Runnable实现的是void run()方法,无返回值
* Callable实现的是 V call()方法,并且可以返回执行结果
* Runnable可以提交给Thread,在包装下直接启动一个线程来执行
* Callable一般都是提交给ExecuteService来执行
*/ 

static void futureDemo() {
try {
Future<?> result1 = executorService.submit(new Runnable() {
public void run() {
fibc(20);
}
});
System.out.println("future result from runnable:"+result1.get());    //run()无返回值所以为空,result1.get()方法会阻塞
Future<Integer> result2 = executorService.submit(new Callable<Integer>()    {
public Integer call() throws Exception {
return fibc(20);    
}
});
System.out.println("future result from callable:"+result2.get());    //call()有返回值,result2.get()方法会阻塞
FutureTask<Integer> result3 = new FutureTask<Integer>(new Callable<Integer>() {
public Integer call() throws Exception {
return fibc(20);
}
});
executorService.submit(result3);    
System.out.println("future result from FutureTask:" + result3.get());    //call()有返回值,result3.get()方法会阻塞

/*因为FutureTask实现了Runnable,因此它既可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行*/
FutureTask<Integer> result4 = new FutureTask<Integer>(new Runnable() {
public void run() {
fibc(20);
}
},fibc(20));    
executorService.submit(result4);
System.out.println("future result from executeService FutureTask :" + result4.get());    //call()有返回值,result3.get()方法会阻塞
//这里解释一下什么FutureTask实现了Runnable结果不为null,这就用到FutureTask对Runnable的包装,所以Runnable注入会被Executors.callable()函数转换成Callable类型

FutureTask<Integer> result5 = new FutureTask<Integer>(new Runnable() {
public void run() {
fibc(20);
}
},fibc(20));
new Thread(result5).start();
System.out.println("future result from Thread FutureTask :" + result5.get());    //call()有返回值,result5.get()方法会阻塞

} catch (Exception e) {
e.printStackTrace();
}finally {
executorService.shutdown();
}
}
static int fibc(int num) {
if (num==0) {
return 0;
}
if (num==1) {
return 1;
}
return fibc(num-1) + fibc(num-2);
}
}

 


 

 

Guess you like

Origin www.cnblogs.com/Transkai/p/11230314.html