第9章 Future
来源:互联网 发布:linux 安装magento2 编辑:程序博客网 时间:2024/05/20 06:29
背景介绍:假设有一个执行起来需要花时间的方法,我们就不需要等待执行结果出来了,而获取一张替代的提货单,这个提货单就Future参与者
注:当采用Thread-Per-Message方式里,需要线程操作的方法做同步控制,保证线程操作的数据的正确性
public class FutureMain {public static void main(String[] args) {System.out.println("main BEGIN"); Host host = new Host(); Data2 data1 = host.request(10, 'A'); Data2 data2 = host.request(20, 'B'); Data2 data3 = host.request(30, 'C'); System.out.println("main otherJob BEGIN"); try { Thread.sleep(2000); } catch (InterruptedException e) { } System.out.println("main otherJob END"); System.out.println("data1 = " + data1.getContent()); System.out.println("data2 = " + data2.getContent()); System.out.println("data3 = " + data3.getContent()); System.out.println("main END");}}interface Data2 { public abstract String getContent();}class RealData implements Data2 { private final String content; public RealData(int count, char c) { System.out.println(" making RealData(" + count + ", " + c + ") BEGIN"); char[] buffer = new char[count]; for (int i = 0; i < count; i++) { buffer[i] = c; try { Thread.sleep(100); } catch (InterruptedException e) { } } System.out.println(" making RealData(" + count + ", " + c + ") END"); this.content = new String(buffer); } public String getContent() { return content; }}class FutureData implements Data2 { private RealData realdata = null; private boolean ready = false; public synchronized void setRealData(RealData realdata) { if (ready) { return; // balk } this.realdata = realdata; this.ready = true; notifyAll(); } public synchronized String getContent() { while (!ready) { try { wait(); } catch (InterruptedException e) { } } return realdata.getContent(); }}class Host { public Data2 request(final int count, final char c) { System.out.println(" request(" + count + ", " + c + ") BEGIN"); // (1) 建立FutureData的实体 final FutureData future = new FutureData(); // (2) 为了建立RealData的实体,启动新的线程 通过Thread-Per-Message方式模拟实现Future new Thread() { public void run() { RealData realdata = new RealData(count, c); future.setRealData(realdata); } }.start(); System.out.println(" request(" + count + ", " + c + ") END"); // (3) 取回FutureData实体,作为传回值 return future; }}
0 0
- 第9章 Future
- 第19章 Future和Promise
- Future
- future
- future
- Future
- Future
- [future]
- Future
- Future
- future
- Future
- future
- 第107讲:Akka中的Future使用代码实战详解学习笔记
- 第七章 Future,Promise and async()——线程通信
- Future Memories
- Technology & Future
- prospactive future
- xcode中使用opencv报各种错误
- c# 自动发送邮件测试代码
- C语言线程池的实现
- 精通 CSS+DIV 网页样式与布局 135
- json数据及追加
- 第9章 Future
- MULE ESB 3.6.0 在linux服务器的发布
- Gson解析json数据
- 精通 CSS+DIV 网页样式与布局 136
- Android日历功能
- xxx cannot be resolved to a type 错误解决方法
- iOS viewDidLoad中更改ImageView位置无效
- Kali2.0 shell终端字体重叠问题
- 为Bootstrap模态对话框添加拖拽移动功能