1 import java.util.ArrayList;
2 import java.util.List;
3 import java.util.concurrent.*;
4 /**
5 * TODO
6 *
7 * @author Cooper
8 * @CreateDate 2023/9/17/14:52
9 */
10 public class demo04 implements Callable<List<String>> {
11 @Override
12 public List<String> call() throws Exception {
13 List<String> result = new ArrayList<>();
14 for (int i = 0; i < 5; i++) {
15 result.add(Thread.currentThread().getName()+"===>"+i);
16 System.out.print(Thread.currentThread().getName()+"===>"+i+"\t");
17 }
18 return result;
19 }
20 public static void main(String[] args) throws ExecutionException, InterruptedException {
21 demo04 test1 = new demo04();
22 demo04 test2 = new demo04();
23 demo04 test3 = new demo04();
24 // 创建服务开启三个线程
25 ExecutorService service = Executors.newFixedThreadPool(3);
26 System.out.println("运行中:");
27 // 提交执行
28 Future<List<String>> r1 = service.submit(test1);
29 Future<List<String>> r2 = service.submit(test2);
30 Future<List<String>> r3 = service.submit(test3);
31 // 获取结果
32 List<String> result1 = r1.get();
33 List<String> result2 = r2.get();
34 List<String> result3 = r3.get();
35 System.out.println();
36
37 System.out.println("运行结束:");
38 System.out.println(result1);
39 System.out.println(result2);
40 System.out.println(result3);
41 // 关闭服务
42 service.shutdown();
43 }
44 }
运行中:
pool-1-thread-2===>0 pool-1-thread-1===>0 pool-1-thread-2===>1 pool-1-thread-3===>0
pool-1-thread-2===>2 pool-1-thread-1===>1 pool-1-thread-2===>3 pool-1-thread-1===>2
pool-1-thread-3===>1 pool-1-thread-1===>3 pool-1-thread-2===>4 pool-1-thread-1===>4
pool-1-thread-3===>2 pool-1-thread-3===>3 pool-1-thread-3===>4
运行结束:
[pool-1-thread-1===>0, pool-1-thread-1===>1, pool-1-thread-1===>2, pool-1-thread-1===>3, pool-1-thread-1===>4]
[pool-1-thread-2===>0, pool-1-thread-2===>1, pool-1-thread-2===>2, pool-1-thread-2===>3, pool-1-thread-2===>4]
[pool-1-thread-3===>0, pool-1-thread-3===>1, pool-1-thread-3===>2, pool-1-thread-3===>3, pool-1-thread-3===>4]