`
aaron_ch
  • 浏览: 177251 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

Future pattern

    博客分类:
  • Java
阅读更多
个人理解 Future 模式就是在主线程中当需要进行比较耗时的作业,但不想阻塞主线程的作业时,将耗时作业交由 Future 对象在后台中完成,当主线程将来(这个 Future 的意义也就体现在这里了)需要时即可通过 Future 对象获得已经作业对象。

这里写了一个简单的例子来说明这种模式,其实写这个例子主要是自己想熟悉一下 JDK5 的 concurrency 包中 FutureTask 的用法了。例子模拟的是一个会计算账的过程,主线程中已经获得其他帐户的总额了,为了不让主线程等待 PrivateAccount 返回而启用新的线程去处理,并使用 FutureTask 对象来监控,最后需要计算总额的时候再尝试去获得 PrivateAccount 的信息。



代码如下:

1 package testCallable;
2
3 import java.util.Random;
4 import java.util.concurrent.Callable;
5 import java.util.concurrent.ExecutionException;
6 import java.util.concurrent.FutureTask;
7
8 /** */ /**
9 * @author chenpengyi
10 */
11 public class SumAccountExample {
12
13 public static void main(String[] args) {
14 // Init callable object and future task
15 Callable pAccount = new PrivateAccount();
16 FutureTask futureTask = new FutureTask(pAccount);
17
18 // Create a new thread to do so
19 Thread pAccountThread = new Thread(futureTask);
20 pAccountThread.start();
21
22 // Do something else in the main thread
23 System.out.println( " Doing something else here. " );
24
25 // Get the total money from other accounts
26 int totalMoney = new Random().nextInt( 100000 );
27 System.out.println( " You have " + totalMoney + " in your other Accounts. " );
28 System.out.println( " Waiting for data from Private Account " );
29 // If the Future task is not finished, we will wait for it
30 while ( ! futureTask.isDone()) {
31 try {
32 Thread.sleep( 5 );
33 } catch (InterruptedException e) {
34 e.printStackTrace();
35 }
36 }
37 Integer privataAccountMoney = null ;
38 // Since the future task is done, get the object back
39 try {
40 privataAccountMoney = (Integer)futureTask.get();
41 } catch (InterruptedException e) {
42 e.printStackTrace();
43 } catch (ExecutionException e) {
44 e.printStackTrace();
45 }
46 System.out.println( " The total moeny you have is " + (totalMoney + privataAccountMoney.intValue()));
47 }
48
49 }
50
51
52 class PrivateAccount implements Callable {
53
54 Integer totalMoney;
55
56 @Override
57 public Integer call() throws Exception {
58 // Simulates a time conusimg task, sleep for 10s
59 Thread.sleep( 10000 );
60 totalMoney = new Integer( new Random().nextInt( 10000 ));
61 System.out.println( " You have " + totalMoney + " in your private Account. " );
62 return totalMoney;
63 }
64
65 }
主线程获得了返回后即完成了总额的计算。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics