码迷,mamicode.com
首页 > 编程语言 > 详细

JavaFuture模式

时间:2018-08-12 23:43:14      阅读:313      评论:0      收藏:0      [点我收藏+]

标签:bsp   运行   row   exception   exce   ram   string   时间   art   

 1 /*
 2  * To change this license header, choose License Headers in Project Properties.
 3  * To change this template file, choose Tools | Templates
 4  * and open the template in the editor.
 5  */
 6 
 7 /**
 8  *
 9  * @author lx
10  */
11 
12 import java.util.concurrent.Callable;
13 import java.util.concurrent.ExecutionException;
14 import java.util.concurrent.FutureTask;
15 
16 public class FutureTackDome {
17 
18     
19     /**
20      * Java Future模式简单使用: 在此案例中模拟,接到到订单数据,并调用支付接口进行支付,支付成功返回2,支付失败返回0
21      * 
22      * @param args
23      * @throws Exception
24      * @throws ExecutionException
25      */
26     public static void main(String[] args) throws Exception, ExecutionException {
27         Callable<Student> callable = () -> {
28                     int id = 0;
29                     System.out.println("调用支付接口");
30                     while (id != 2) {
31                         Thread.sleep(5000);//模拟支付時間
32                         System.out.println("正在查询付款状态...");
33                         System.out.println("状态为:" + id);
34                         id++;
35                     }
36                     
37                     if (id == 2) {
38                         // 付款成功
39                         return new Student(id);
40                         
41                     } else {
42                         // 付款失败
43                         return new Student(0);
44                     }
45                 };
46         FutureTask<Student> futureTask = new FutureTask<>(callable);
47         new Thread(futureTask).start();
48 
49         while (futureTask.isDone()) {// 模拟等待支付状态回调
50 
51         }
52         System.out.println((futureTask.get().getId() == 2 ? "支付成功" : "支付失败"));
53 
54     }
55 }
56 //实体类
57 class Student {
58     Student() {
59 
60     }
61 
62     public Student(int id) {
63         super();
64         this.id = id;
65     }
66 
67     private int id;
68 
69     public int getId() {
70         return id;
71     }
72 
73     public void setId(int id) {
74         this.id = id;
75     }
76 
77     @Override
78     public String toString() {
79         return "Student [id=" + id + "]";
80     }
81 
82 }
83 
84 运行示例:
85 run:
86 调用支付接口
87 正在查询付款状态...
88 状态为:0
89 正在查询付款状态...
90 状态为:1
91 支付成功
92 成功构建 (总时间: 10 秒)

 

JavaFuture模式

标签:bsp   运行   row   exception   exce   ram   string   时间   art   

原文地址:https://www.cnblogs.com/mature1021/p/9465330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!