设为首页 加入收藏

TOP

Java多线程学习(Day02)(二)
2023-09-23 15:44:15 】 浏览:106
Tags:Java 程学习 Day02
人拿到了! 这就是线程不安全,数据紊乱。后序我们将通过线程同步解决这个问题。

方式三:实现callable接口(了解即可)

 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]

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Nginx + Spring Boot 轻松实现负.. 下一篇2023年了,复习了一下spring boot..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目