Java多线程(有返回值)的使用

一.实现 Callable接口,重写call()方法

 1 import com.google.common.collect.Lists;
 2 import java.util.List;
 3 import java.util.concurrent.Callable;
 4 import java.util.concurrent.ExecutorService;
 5 import java.util.concurrent.Executors;
 6 import java.util.concurrent.Future;
 7 
 8 public class JustTest2 {
 9     public static void main(String[] args) {
10         Callable callable = null;
11         //创建大小为5的线程池
12         ExecutorService executor = Executors.newFixedThreadPool(5);
13         List> results = Lists.newArrayList();
14 
15         for (int i = 0; i < 10; i++) {
16             callable = new TestCallable("data1", "data2",String.valueOf(i));
17             Future result = executor.submit(callable);
18             //把结果都放入results集合中
19             results.add(result);
20         }
21         //关闭线程池
22         executor.shutdown();
23 
24         for (Future result : results) {
25             try {
26                 //get()获取 返回的结果
27                 System.out.println(result.get());
28             } catch (Exception e) {
29             }
30         }
31     }
32 
33 }
34 
35 /**
36  * 内部类:实现Callable接口
37  * 重写call()方法
38  */
39 class TestCallable implements Callable {
40     private String data1;
41     private String data2;
42     private String flag;
43 
44     public TestCallable(String data1, String data2,String flag) {
45         this.data1 = data1;
46         this.data2 = data2;
47         this.flag = flag;
48     }
49 
50     @Override
51     public String call() {
52         if(flag.equals("1")){
53             return data1;
54         }
55         return data2;
56     }
57 }

二,运行结果为

Java多线程(有返回值)的使用_第1张图片

 

转载于:https://www.cnblogs.com/yy136/p/8324306.html

你可能感兴趣的:(Java多线程(有返回值)的使用)