java线程池之synchronized锁

 1  //Object 定义了一个引用类型的对象用于加锁
 2     static Object Lock = new Object();
 3     //定义一个int类型变量0做初始值
 4     static int iCheck = 0;
 5 
 6     public static void main(String[] args) {
 7         //第一个线程
 8         int a = 0;
 9         //创建一个数组保存打印的数值
10         List<Integer> list = new ArrayList<>();
11         //设置线程池大小为4
12         ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
13         //i从0开始递增1,直到小于1000跳出循环
14         for (int i = 0; i < 1000; i++) {
15             list.add(a);
16             a++;
17         }
18         //循环触发4个任务丢给线程池处理
19         for (int i = 0; i < list.size(); i++) {
20             int z = list.get(i);
21             //把任务交给线程池
22             fixedThreadPool.execute(() -> {
23                 Test(z);
24             });
25         }
26     }
27 
28     public static void Test(int z) {
29         try {
30             do {
31                 //从0开始递增,
32                 if (iCheck == z) {
33                     synchronized (Lock) {
34                         //输出线程名称和当前值
35                         System.out.println(Thread.currentThread().getName() + " " + z);
36                         iCheck += 1;
37                     }
38                     break;
39                 }
40                 //让出cup时间给其他满足条件的线程执行
41                 Thread.yield();
42 
43             } while (true);
44             //每个线程休息1秒后继续工作,4个线程完成循环后第一个线程继续工作
45             Thread.sleep(1000);
46         } catch (InterruptedException e) {
47         }
48     }

pool-1-thread-1 0
pool-1-thread-2 1
pool-1-thread-3 2
pool-1-thread-4 3
pool-1-thread-1 4
pool-1-thread-3 5
pool-1-thread-4 6
pool-1-thread-2 7
pool-1-thread-1 8

打印结果顺序输出

 

posted @ 2019-03-27 20:07  咯咯呀  阅读(1370)  评论(0编辑  收藏  举报