API:
Java代码
public interface Executor {
void execute(Runnable command);
}
public interface ExecutorService extends Executor {
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
...
}
public class FutureTask<V> extends Object
implements Future<V>, Runnable
FutureTask(Callable<V> callable)
//创建一个 FutureTask,一旦运行就执行给定的 Callable。
FutureTask(Runnable runnable, V result)
//创建一个 FutureTask,一旦运行就执行给定的 Runnable,并安排成功完成时 get 返回给定的结果 。
/*参数:
runnable - 可运行的任务。
result - 成功完成时要返回的结果。
如果不需要特定的结果,则考虑使用下列形式的构造:Future<?> f = new FutureTask<Object>(runnable, null) */
如果不需要特定的结果,则考虑使用下列形式的构造:Future<?> f = new FutureTask<Object>(runnable, null) */
FutureTask多用于耗时的计算,主线程可以在完成自己的任务后,再去获取结果。
单独使用Runnable时:
无法获得返回值
单独使用Callable时:
无法在新线程中(new Thread(Runnable r))使用,只能使用ExecutorService
Thread类只支持Runnable
FutureTask:
实现了Runnable和Future,所以兼顾两者优点
既可以使用ExecutorService,也可以使用Thread
Java代码
Callable pAccount = new PrivateAccount();
FutureTask futureTask = new FutureTask(pAccount);
// 使用futureTask创建一个线程
Thread thread = new Thread(futureTask);
thread.start();
Callable pAccount = new PrivateAccount();
FutureTask futureTask = new FutureTask(pAccount);
// 使用futureTask创建一个线程
Thread thread = new Thread(futureTask);
thread.start();
=================================================================
public interface Future<V> Future 表示异步计算的结果。
Future有个get方法而获取结果只有在计算完成时获取,否则会一直阻塞直到任务转入完成状态,然后会返回结果或者抛出异常。
FutureTask是为了弥补Thread的不足而设计的,它可以让程序员准确地知道线程什么时候执行完成并获得到线程执行完成后返回的结果(如果有需要)。
FutureTask是一种可以取消的异步的计算任务。它的计算是通过Callable实现的,它等价于可以携带结果的Runnable,并且有三个状态:等待、运行和完成。完成包括所有计算以任意的方式结束,包括正常结束、取消和异常。
Future 主要定义了5个方法:
1)boolean cancel(boolean mayInterruptIfRunning):试图取消对此任务的执行。如果任务已完成、或已取消,或者由于某些其他原因而无法取消,则此尝试将失败。当调用 cancel 时,如果调用成功,而此任务尚未启动,则此任务将永不运行。如果任务已经启动,则 mayInterruptIfRunning 参数确定是否应该以试图停止任务的方式来中断执行此任务的线程。此方法返回后,对 isDone() 的后续调用将始终返回 true。如果此方法返回 true,则对 isCancelled() 的后续调用将始终返回 true。
2)boolean isCancelled():如果在任务正常完成前将其取消,则返回 true。
3)boolean isDone():如果任务已完成,则返回 true。 可能由于正常终止、异常或取消而完成,在所有这些情况中,此方法都将返回 true。
4)V get()throws InterruptedException,ExecutionException:如有必要,等待计算完成,然后获取其结果。
5)V get(long timeout,TimeUnit unit) throws InterruptedException,ExecutionException,TimeoutException:如有必要,最多等待为使计算完成所给定的时间之后,获取其结果(如果结果可用)。
Java代码
public class FutureTask<V> extends Object
implements Future<V>, Runnable
public class FutureTask<V> extends Object
implements Future<V>, Runnable FutureTask类是Future 的一个实现,并实现了Runnable,所以可通过Excutor(线程池) 来执行,也可传递给Thread对象执行。如果在主线程中需要执行比较耗时的操作时,但又不想阻塞主线程时,可以把这些作业交给Future对象在后台完成,当主线程将来需要时,就可以通过Future对象获得后台作业的计算结果或者执行状态。
Executor框架利用FutureTask来完成异步任务,并可以用来进行任何潜在的耗时的计算。一般FutureTask多用于耗时的计算,主线程可以在完成自己的任务后,再去获取结果。
JDK:
此类提供了对 Future 的基本实现。仅在计算完成时才能检索结果;如果计算尚未完成,则阻塞 get 方法。一旦计算完成,就不能再重新开始或取消计算。
可使用 FutureTask 包装 Callable 或 Runnable 对象。因为 FutureTask 实现了 Runnable,所以可将 FutureTask 提交给 Executor 执行。
Java代码
构造方法摘要
FutureTask(Callable<V> callable)
创建一个 FutureTask,一旦运行就执行给定的 Callable。
FutureTask(Runnable runnable, V result)
创建一个 FutureTask,一旦运行就执行给定的 Runnable,并安排成功完成时 get 返回给定的结果 。
参数:
runnable - 可运行的任务。
result - 成功完成时要返回的结果。
如果不需要特定的结果,则考虑使用下列形式的构造:Future<?> f = new FutureTask<Object>(runnable, null)
构造方法摘要
FutureTask(Callable<V> callable)
创建一个 FutureTask,一旦运行就执行给定的 Callable。
FutureTask(Runnable runnable, V result)
创建一个 FutureTask,一旦运行就执行给定的 Runnable,并安排成功完成时 get 返回给定的结果 。
参数:
runnable - 可运行的任务。
result - 成功完成时要返回的结果。
如果不需要特定的结果,则考虑使用下列形式的构造:Future<?> f = new FutureTask<Object>(runnable, null)
Example1:
下面的例子模拟一个会计算账的过程,主线程已经获得其他帐户的总额了,为了不让主线程等待 PrivateAccount类的计算结果的返回而启用新的线程去处理, 并使用 FutureTask对象来监控,这样,主线程还可以继续做其他事情, 最后需要计算总额的时候再尝试去获得privateAccount 的信息。
Java代码
package test;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
*
* @author Administrator
*
*/
@SuppressWarnings("all")
public class FutureTaskDemo {
public static void main(String[] args) {
// 初始化一个Callable对象和FutureTask对象
Callable pAccount = new PrivateAccount();
FutureTask futureTask = new FutureTask(pAccount);
// 使用futureTask创建一个线程
Thread pAccountThread = new Thread(futureTask);
System.out.println("futureTask线程现在开始启动,启动时间为:" + System.nanoTime());
pAccountThread.start();
System.out.println("主线程开始执行其他任务");
// 从其他账户获取总金额
int totalMoney = new Random().nextInt(100000);
System.out.println("现在你在其他账户中的总金额为" + totalMoney);
System.out.println("等待私有账户总金额统计完毕...");
// 测试后台的计算线程是否完成,如果未完成则等待
while (!futureTask.isDone()) {
try {
Thread.sleep(500);
System.out.println("私有账户计算未完成继续等待...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("futureTask线程计算完毕,此时时间为" + System.nanoTime());
Integer privateAccountMoney = null;
try {
privateAccountMoney = (Integer) futureTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("您现在的总金额为:" + totalMoney + privateAccountMoney.intValue());
}
}
@SuppressWarnings("all")
class PrivateAccount implements Callable {
Integer totalMoney;
@Override
public Object call() throws Exception {
Thread.sleep(5000);
totalMoney = new Integer(new Random().nextInt(10000));
System.out.println("您当前有" + totalMoney + "在您的私有账户中");
return totalMoney;
}
}
package test;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
*
* @author Administrator
*
*/
@SuppressWarnings("all")
public class FutureTaskDemo {
public static void main(String[] args) {
// 初始化一个Callable对象和FutureTask对象
Callable pAccount = new PrivateAccount();
FutureTask futureTask = new FutureTask(pAccount);
// 使用futureTask创建一个线程
Thread pAccountThread = new Thread(futureTask);
System.out.println("futureTask线程现在开始启动,启动时间为:" + System.nanoTime());
pAccountThread.start();
System.out.println("主线程开始执行其他任务");
// 从其他账户获取总金额
int totalMoney = new Random().nextInt(100000);
System.out.println("现在你在其他账户中的总金额为" + totalMoney);
System.out.println("等待私有账户总金额统计完毕...");
// 测试后台的计算线程是否完成,如果未完成则等待
while (!futureTask.isDone()) {
try {
Thread.sleep(500);
System.out.println("私有账户计算未完成继续等待...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("futureTask线程计算完毕,此时时间为" + System.nanoTime());
Integer privateAccountMoney = null;
try {
privateAccountMoney = (Integer) futureTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("您现在的总金额为:" + totalMoney + privateAccountMoney.intValue());
}
}
@SuppressWarnings("all")
class PrivateAccount implements Callable {
Integer totalMoney;
@Override
public Object call() throws Exception {
Thread.sleep(5000);
totalMoney = new Integer(new Random().nextInt(10000));
System.out.println("您当前有" + totalMoney + "在您的私有账户中");
return totalMoney;
}
}
运行结果
来源:
http://zheng12tian.iteye.com/blog/991484
Example2:
Java代码
public class FutureTaskSample {
static FutureTask<String> future = new FutureTask(new Callable<String>(){
public String call(){
return getPageContent();
}
});
public static void main(String[] args) throws InterruptedException, ExecutionException{
//Start a thread to let this thread to do the time exhausting thing
new Thread(future).start();
//Main thread can do own required thing first
doOwnThing();
//At the needed time, main thread can get the result
System.out.println(future.get());
}
public static String doOwnThing(){
return "Do Own Thing";
}
public static String getPageContent(){
return "Callable method...";
}
}
public class FutureTaskSample {
static FutureTask<String> future = new FutureTask(new Callable<String>(){
public String call(){
return getPageContent();
}
});
public static void main(String[] args) throws InterruptedException, ExecutionException{
//Start a thread to let this thread to do the time exhausting thing
new Thread(future).start();
//Main thread can do own required thing first
doOwnThing();
//At the needed time, main thread can get the result
System.out.println(future.get());
}
public static String doOwnThing(){
return "Do Own Thing";
}
public static String getPageContent(){
return "Callable method...";
}
} 结果为:Callable method...
来源:http://tomyz0223.iteye.com/blog/1019924
改为这样,结果就正常:
Java代码
public class FutureTaskSample {
public static void main(String[] args) throws InterruptedException, ExecutionException{
//Start a thread to let this thread to do the time exhausting thing
Callable call = new MyCallable();
FutureTask future = new FutureTask(call);
new Thread(future).start();
//Main thread can do own required thing first
//doOwnThing();
System.out.println("Do Own Thing");
//At the needed time, main thread can get the result
System.out.println(future.get());
}
}
class MyCallable implements Callable<String>{
@Override
public String call() throws Exception {
return getPageContent();
}
public String getPageContent(){
return "Callable method...";
}
}
public class FutureTaskSample {
public static void main(String[] args) throws InterruptedException, ExecutionException{
//Start a thread to let this thread to do the time exhausting thing
Callable call = new MyCallable();
FutureTask future = new FutureTask(call);
new Thread(future).start();
//Main thread can do own required thing first
//doOwnThing();
System.out.println("Do Own Thing");
//At the needed time, main thread can get the result
System.out.println(future.get());
}
}
class MyCallable implements Callable<String>{
@Override
public String call() throws Exception {
return getPageContent();
}
public String getPageContent(){
return "Callable method...";
}
} 结果:
Do Own Thing
Callable method...
Example3:
Java代码
import java.util.concurrent.Callable;
public class Changgong implements Callable<Integer>{
private int hours=12;
private int amount;
@Override
public Integer call() throws Exception {
while(hours>0){
System.out.println("I'm working......");
amount ++;
hours--;
Thread.sleep(1000);
}
return amount;
}
}
import java.util.concurrent.Callable;
public class Changgong implements Callable<Integer>{
private int hours=12;
private int amount;
@Override
public Integer call() throws Exception {
while(hours>0){
System.out.println("I'm working......");
amount ++;
hours--;
Thread.sleep(1000);
}
return amount;
}
}
Java代码
public class Dizhu {
public static void main(String args[]){
Changgong worker = new Changgong();
FutureTask<Integer> jiangong = new FutureTask<Integer>(worker);
new Thread(jiangong).start();
while(!jiangong.isDone()){
try {
System.out.println("看长工做完了没...");
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int amount;
try {
amount = jiangong.get();
System.out.println("工作做完了,上交了"+amount);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Dizhu {
public static void main(String args[]){
Changgong worker = new Changgong();
FutureTask<Integer> jiangong = new FutureTask<Integer>(worker);
new Thread(jiangong).start();
while(!jiangong.isDone()){
try {
System.out.println("看长工做完了没...");
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int amount;
try {
amount = jiangong.get();
System.out.println("工作做完了,上交了"+amount);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
结果:
看工人做完了没...
I'm working......
看工人做完了没...
I'm working......
看工人做完了没...
I'm working......
看工人做完了没...
I'm working......
看工人做完了没...
I'm working......
看工人做完了没...
I'm working......
看工人做完了没...
I'm working......
看工人做完了没...
I'm working......
看工人做完了没...
I'm working......
看工人做完了没...
I'm working......
看工人做完了没...
I'm working......
看工人做完了没...
I'm working......
看工人做完了没...
工作做完了,上交了12