1+ package org .javacore .thread ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .concurrent .Callable ;
5+ import java .util .concurrent .ExecutionException ;
6+ import java .util .concurrent .ExecutorService ;
7+ import java .util .concurrent .Executors ;
8+ import java .util .concurrent .Future ;
9+ /**
10+ * Created by BYSocket on 2015/11/2.
11+ *
12+ * Copyright [2015] [Jeff Lee]
13+ *
14+ * Licensed under the Apache License, Version 2.0 (the "License");
15+ * you may not use this file except in compliance with the License.
16+ * You may obtain a copy of the License at
17+ *
18+ * http://www.apache.org/licenses/LICENSE-2.0
19+ *
20+ * Unless required by applicable law or agreed to in writing, software
21+ * distributed under the License is distributed on an "AS IS" BASIS,
22+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23+ * See the License for the specific language governing permissions and
24+ * limitations under the License.
25+ */
26+
27+ /**
28+ * @author Jeff Lee
29+ * @since 2015-11-2 18:58:36
30+ * Callable接口的使用 --- 实现带返回值的任务
31+ */
32+
33+ // Callable实现类task,指定其类型参数
34+ class TaskWithResult implements Callable <String > {
35+
36+ private int id ;
37+ public TaskWithResult (int id ) {
38+ this .id = id ;
39+ }
40+
41+ @ Override
42+ public String call () throws Exception {
43+ return "result of TaskWithResult " + id ;
44+ }
45+ }
46+
47+ public class CallableDemo {
48+ public static void main (String [] args ) {
49+ // 创建一个新的线程池
50+ ExecutorService exec = Executors .newCachedThreadPool ();
51+ // Callable实现类task的返回结果集
52+ ArrayList <Future <String >> results = new ArrayList <>();
53+ for (int i = 0 ; i < 5 ; i ++)
54+ results .add (exec .submit (new TaskWithResult (i )));// 使用submit来启动Tasks
55+
56+ // 异步计算的结果
57+ for (Future <String > fs : results )
58+ try {
59+ // get阻塞,直至获取结果
60+ System .out .println (fs .get ());
61+ } catch (InterruptedException e ) {
62+ System .out .println (e );
63+ e .printStackTrace ();
64+ } catch (ExecutionException e ) {
65+ System .out .println (e );
66+ e .printStackTrace ();
67+ } finally {
68+ exec .shutdown ();
69+ }
70+ }
71+ }
0 commit comments