前面已经介绍过future模式和jdk5中的future,在jdk5中对future有个基本实现,这个实现就是类futuretask。
对于future模式,每个人都有自己的理解。这里引用他人的话,做个理解:
“Future 模式就是在主线程中当需要进行比较耗时的作业,但不想阻塞主线程的作业时,将耗时作业交由 Future 对象在后台中完成,当主线程将来(这个 Future 的意义也就体现在这里了)需要时即可通过 Future 对象获得已经作业对象。”
下面举个例子,来加深理解,:)其实,看代码容易理解。
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class testFutureTask {
public static void main(String[] args) {
// Init callable object and future task
Callable pAccount = new PrivateAccount();
FutureTask futureTask = new FutureTask(pAccount);
// Create a new thread to do so
Thread pAccountThread = new Thread(futureTask);
//this will call the method call of PrivateAccount
pAccountThread.start();
// Do something else in the main thread
System.out.println(" Doing something else here. ");
// Get the total money from other accounts
int totalMoney = new Random().nextInt(100000);
System.out.println(" You have " + totalMoney
+ " in your other Accounts. ");
System.out.println(" Waiting for data from Private Account ");
// If the Future task is not finished, we will wait for it
while (!futureTask.isDone()) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Integer privataAccountMoney = null;
// Since the future task is done, get the object back
try {
privataAccountMoney = (Integer) futureTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(" The total moeny you have is "
+ (totalMoney + privataAccountMoney.intValue()));
}
}
import java.util.Random;
import java.util.concurrent.Callable;
public class PrivateAccount implements Callable {
Integer totalMoney;
public Integer call() throws Exception {
// Simulates a time conusimg task, sleep for 10s
Thread.sleep(10000);
totalMoney = new Integer(new Random().nextInt(10000));
System.out.println(" You have " + totalMoney
+ " in your private Account. ");
return totalMoney;
}
}
从上面的代码可以看出有了futuretask,利用future模式完成任务还是很方便的。