`
aaron_ch
  • 浏览: 178146 次
  • 性别: 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 }
主线程获得了返回后即完成了总额的计算。
分享到:
评论

相关推荐

    Future Patter 改进了一点点的代码

    对结城浩的Future Pattern的代码做了一点儿小小的改进(见blog)。

    JAVA并发编程实践 EN(全)

    6. **并发编程模式**:介绍如双检锁/双重校验锁(DCL)、生产者消费者模式、读写锁、未来的值(Future Pattern)等并发编程模式,帮助开发者解决实际问题。 7. **线程通信**:讲解wait()、notify()和notifyAll()...

    Pattern Recognition using Neural and Functional Networks(Springer2009新书)

    - Potential future applications and implications for the field of pattern recognition. #### Conclusion *Pattern Recognition Using Neural and Functional Networks* offers a detailed exploration of ...

    Pattern Oriented Software Architecture Volume 3 - Patterns for Resource

    10. **第8章 - 模式的过去、现在与未来**(Chapter 8 - The Past, Present, and Future of Patterns): - 分析了设计模式的发展历程、当前状态以及未来趋势。这部分内容有助于读者了解设计模式的历史背景及其在...

    Nine Algorithms That Changed the Future

    Search Engine Indexing, PageRank, Public Key Cryptography, Error-Correcting Codes, Pattern Recognition, Data Compression, Databases, Digital Signatures, What is Computable? 计算机和非计算机人士都可以...

    Signal Processing,Image Processing,and Pattern Recognition

    英文 pdf 参考资料 International Conference, SIP 2009 Held as Part of the Future Generation Information Technology Conference, FGIT 2009 Jeju Island, Korea, December 10-12, 2009 Proceedings

    Signal_Processing_Image_Processing_and_Pattern_Recognition

    As future generation information technology (FGIT) becomes specialized and fragmented, it is easy to lose sight that many topics in FGIT have common threads and, because of this, advances in one ...

    良葛格DesignPattern学习笔记

    良葛格的《Design Pattern学习笔记》不仅涵盖了经典的GOF设计模式,还额外介绍了几种多线程模式,这使得这份学习笔记成为了一个宝贵的学习资源。下面将对其中的部分设计模式进行详细介绍。 #### 二、GOF设计模式 ...

    这个才是POSA4英文

    1. **模式概念**:模式是解决特定问题的可重用解决方案,POSA4介绍了适用于并发和分布式计算的模式,如Actor模型、Monitor、Future和Promise等。 2. **并发编程**:书中深入探讨了并发编程中的挑战,如死锁、活锁、...

    Thinning methodologies-a comprehensive survey

    The comprehensive nature of the survey makes it a valuable resource for anyone interested in understanding the current state and future prospects of thinning methodologies in the realm of pattern ...

    The hub network design problem

    Hub(枢纽,或转运中心)允许通过货物集散和中转,降低网络连接的数量,从而构建大的运输网络,即所谓的Hub-and-spoke(轴辐式网络),该组网方式能够简化网络复杂性,降低建设成本,并集中分拣和处理货物,并整合流量...

    A survey on face detection in the wild-Past, present and future

    常见的特征提取方法包括Haar特征、LBP(Local Binary Pattern)、HOG(Histogram of Oriented Gradients)等。这些特征能够捕捉到图像中的局部信息,为后续的分类提供支持。 ##### 3.2 Boosting算法 Boosting算法是一...

    Perspectives on Spatial Data Analysis-Arthur Getis-空间数据分析-英文原版

    methods developed to deal with problems of spatial pattern recognition, spatial autocorrelation, and spatial heterogeneity have seen greatly increased adoption, in part due to the availability of user...

    Cloud.Computing.Design.Patterns.9332557306.epub

    I will use this text as a resource in future cloud designs and architectural considerations.” –Dr. Nancy M. Landreville, CEO/CISO, NML Computer Consulting The authors address topics covering ...

    Effective Akka

    The book also includes examples of actor application types and two primary patterns of actor usage, the Extra Pattern and Cameo Pattern., Allen, the Director of Consulting for Typesafe—creator of ...

    Professional ASP.NET Design Patterns

    A sample application used throughout the book is an enterprise level ASP.NET website with multi-tiered, SOA design techniques that can be applied to your future ASP.NET projects. Read about each ...

    DDR package

    These packages feature a predefined ball-out pattern and a straightforward addressing scheme that simplifies the design process for future memory upgrades. The use of FBGA packages ensures ...

Global site tag (gtag.js) - Google Analytics