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

打印結果順序輸出

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM