假设有一个方法需要花费很长时间才能获取运行结果。
那么,与其一直等待结果,不如先拿一张“提货单”。
获取提货单并不耗费时间。
过一段时间后再来拿结果.
public static void main(String[] args) { Host host = new Host(); // 预定蛋糕 FutureData futureData = host.provideCake("didi"); FutureData futureData1 = host.provideCake("dog"); FutureData futureData2 = host.provideCake("cat"); FutureData futureData3 = host.provideCake("bear"); // 取蛋糕 System.out.println(futureData.getData()); System.out.println(futureData1.getData()); System.out.println(futureData2.getData()); System.out.println(futureData3.getData()); }中间人
public class Host { public FutureData provideCake(String cakeName) { // 开提货单 FutureData futureData = new FutureData(); // 通知师傅做蛋糕 new Thread(() -> { RealData realData = new Worker().makeCake(cakeName); // 将蛋糕发给顾客 futureData.setData(realData); }).start(); // 返回提货单 return futureData; } }蛋糕师傅
public class Worker { public RealData makeCake(String cakeName) { RealData realData = new RealData(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } realData.setContent(cakeName); return realData; } }提货单
public class FutureData { // 蛋糕 private String content; public synchronized void setData(RealData realData) { this.content = realData.getContent(); notifyAll(); } public synchronized String getData() { // 如果蛋糕还没有做好, 就等待 if (content == null) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } return this.content; } }蛋糕实体类
public class RealData { private String content; public void setContent(String content) { this.content = content; } public String getContent() { return this.content; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)