File tree Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ package chapter5 ;
2+
3+ import java .util .concurrent .ExecutionException ;
4+ import java .util .concurrent .ExecutorService ;
5+ import java .util .concurrent .Executors ;
6+ import java .util .concurrent .FutureTask ;
7+
8+ /**
9+ * Created by 13 on 2017/5/8.
10+ */
11+ public class FutureMain {
12+
13+ public static void main (String args []) throws ExecutionException , InterruptedException {
14+ //构造FutureTask
15+ FutureTask <String > futureTask = new FutureTask <String >(new RealData2 ("a" ));
16+
17+ ExecutorService executorService = Executors .newFixedThreadPool (1 );
18+
19+ //执行FutureTask,相当于前一个例子中的client.request("a")发送请求
20+ //在这里开启线程进行RealData的call()执行
21+ executorService .submit (futureTask );
22+
23+ System .out .println ("请求完毕" );
24+
25+ try {
26+ //这里依然可以做额外的数据操作,使用sleep代替其他业务逻辑的处理
27+ Thread .sleep (2000 );
28+ } catch (InterruptedException e ) {
29+ e .printStackTrace ();
30+ }
31+
32+ //相当于前一个例子中的data.getResult(),取得call()方法的返回值
33+ //如果此时call()方法没有执行完成,则依然会等待
34+ System .out .println ("数据=" + futureTask .get ());
35+ }
36+ }
Original file line number Diff line number Diff line change 1+ package chapter5 ;
2+
3+ import java .util .concurrent .Callable ;
4+
5+ /**
6+ * Created by 13 on 2017/5/8.
7+ */
8+ public class RealData2 implements Callable <String > {
9+ private String data ;
10+
11+ public RealData2 (String data ) {
12+ this .data = data ;
13+ }
14+
15+ @ Override
16+ public String call () throws Exception {
17+ StringBuffer stringBuffer = new StringBuffer ();
18+ for (int i = 0 ; i < 10 ; i ++) {
19+ stringBuffer .append (data );
20+ Thread .sleep (100 );
21+ }
22+
23+ return stringBuffer .toString ();
24+ }
25+ }
You can’t perform that action at this time.
0 commit comments