多線程使用的一些例子

一、例子1:    

 1 package com.cy.test.thread;
 2 
 3 
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 import java.util.concurrent.CountDownLatch;
 7 import java.util.concurrent.ExecutorService;
 8 import java.util.concurrent.Executors;
 9 
10 public class TestMultiThread {
11     /**
12      * n = 核心數*2 + 1
13      */
14     private static ExecutorService pool = Executors.newFixedThreadPool(5);
15 
16     /**
17      * 1.模擬,使用多線程,找到每個學生的老師名字,並且打印出來。
18      * @param args
19      */
20     public static void main(String[] args) {
21         long begin = System.currentTimeMillis();
22 
23         List<String> studentList = new ArrayList<>();
24         studentList.add("zhangsan");
25         studentList.add("lisi");
26         studentList.add("wangwu");
27 
28         try {
29             CountDownLatch latch = new CountDownLatch(studentList.size());
30             doFindTeacher(studentList, latch);
31             latch.await();
32         } catch (InterruptedException e) {
33             e.printStackTrace();
34         }
35 
36         System.out.println("執行完畢,耗時:" + (System.currentTimeMillis() - begin) + "ms");
37         pool.shutdown();
38     }
39 
40     private static void doFindTeacher(List<String> studentList, CountDownLatch latch) {
41         for(String student : studentList){
42             pool.execute(() -> {
43                 System.out.println("開始處理學生:" + student);
44                 //模擬查數據庫...等操作,查找學生的老師
45                 try {
46                     Thread.sleep(3000);
47                 } catch (InterruptedException e) {
48                     e.printStackTrace();
49                 }
50                 System.out.println("teacher: " + student + "'s teacher");
51 
52                 latch.countDown();
53             });
54         }
55     }
56 }

console:

開始處理學生:zhangsan
開始處理學生:lisi
開始處理學生:wangwu
teacher: lisi's teacher
teacher: zhangsan's teacher
teacher: wangwu's teacher
執行完畢,耗時:3081ms

 

二、例子2:    

 1 package com.cy.test.thread;
 2 
 3 
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 import java.util.concurrent.CountDownLatch;
 7 import java.util.concurrent.ExecutorService;
 8 import java.util.concurrent.Executors;
 9 
10 public class TestMultiThread2 {
11     private static int minProcessCnt = 1;
12     private static int poolSize = 5;
13     private static ExecutorService pool = Executors.newFixedThreadPool(poolSize);
14 
15     /**
16      * 1.模擬,使用多線程,找到每個學生的老師名字,並且打印出來。
17      * @param args
18      */
19     public static void main(String[] args) {
20         long begin = System.currentTimeMillis();
21 
22         List<String> studentList = new ArrayList<>();
23         studentList.add("zhangsan");
24         studentList.add("lisi");
25         studentList.add("wangwu");
26 
27         int perCnt = studentList.size() / poolSize;             //每個線程處理的數量
28         int step = Math.max(perCnt, minProcessCnt);             //每個線程處理的數量,按照step切割list
29         int latchNum = (studentList.size() + step - 1) / step;  //處理次數 (和分頁計算方法一樣:pageCount = (totalCount + pageSize - 1)/pageSize )
30         CountDownLatch latch = new CountDownLatch(latchNum);
31 
32         //切割studentList,分批查詢
33         try {
34             for (int i = 0, start = 0; i < latchNum; i++) {
35                 if(i == latchNum - 1){
36                     doFindTeacher(studentList.subList(start, studentList.size()), latch);
37                 }else{
38                     doFindTeacher(studentList.subList(start, start+step), latch);
39                     start = start + step;
40                 }
41             }
42 
43             latch.await();
44         } catch (InterruptedException e) {
45             e.printStackTrace();
46         }
47 
48         System.out.println("執行完成,耗時:" + (System.currentTimeMillis() - begin) + "ms");
49 
50         pool.shutdown();
51     }
52 
53     private static void doFindTeacher(List<String> studentList, CountDownLatch latch){
54         pool.execute(() -> {
55             try{
56                 for(String student : studentList){
57                     System.out.println("開始處理學生:" + student);
58 
59                     //模擬查數據庫...等操作,查找學生的老師
60                     Thread.sleep(3000);
61                     System.out.println("teacher: " + student + "'s teacher");
62                 }
63             }catch (Exception e){
64                 e.printStackTrace();
65             }finally {
66                 latch.countDown();
67             }
68         });
69     }
70 
71 
72 }

 

開始處理學生:wangwu
開始處理學生:zhangsan
開始處理學生:lisi
teacher: zhangsan's teacher
teacher: wangwu's teacher
teacher: lisi's teacher
執行完成,耗時:3094ms

 

三、例子3:    

 1 package com.cy.test.thread;
 2 
 3 
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 import java.util.concurrent.ExecutorService;
 7 import java.util.concurrent.Executors;
 8 import java.util.concurrent.FutureTask;
 9 
10 public class TestMultiThread3 {
11     private static int minProcessCnt = 1;
12     private static int poolSize = 5;
13     private static ExecutorService pool = Executors.newFixedThreadPool(poolSize);
14 
15     /**
16      * 1.模擬,使用多線程,找到每個學生的老師名字
17      * 2.將老師們的名字返回,並且輸出
18      * @param args
19      */
20     public static void main(String[] args) {
21         long begin = System.currentTimeMillis();
22 
23         List<String> studentList = new ArrayList<>();
24         studentList.add("zhangsan");
25         studentList.add("lisi");
26         studentList.add("wangwu");
27 
28         int size = studentList.size();
29         int perCnt = size / poolSize;
30         int step = Math.max(perCnt, minProcessCnt);
31         int pollCount = (size + step - 1) / step;       // 列表循環次數
32 
33         List<FutureTask<List<String>>> taskList = new ArrayList<>();
34         for (int i = 0; i < pollCount; i++) {
35             final int start = step * i;
36             final int end = (i == pollCount - 1) ? size : step * (i + 1);
37             FutureTask<List<String>> task = new FutureTask<>(() -> {
38                 return doFindTeacher(studentList, start, end);
39             });
40             taskList.add(task);
41             pool.execute(task);
42         }
43 
44         //拿到返回結果
45         List<String> teacherList = new ArrayList<>();
46         try {
47             for (FutureTask<List<String>> futureTask : taskList) {
48                 List<String> list = futureTask.get();
49                 teacherList.addAll(list);
50             }
51         }catch (Exception e){
52             e.printStackTrace();
53         }
54 
55         System.out.println(teacherList);
56 
57         System.out.println("TestMultiThread3 執行完成,耗時:" + (System.currentTimeMillis() - begin) + "ms");
58         pool.shutdown();
59     }
60 
61 
62     private static List<String> doFindTeacher(List<String> studentList, int start, int end) throws InterruptedException {
63         List<String> teacherList = new ArrayList<>();
64         for(int j=start; j<end; j++){
65             String student = studentList.get(j);
66             System.out.println("開始處理學生:" + student);
67 
68             //模擬查數據庫...等操作,查找學生的老師
69             Thread.sleep(3000);
70             String teacher = student + "'s teacher";
71             teacherList.add(teacher);
72         }
73         return teacherList;
74     }
75 }

console:

1 開始處理學生:zhangsan
2 開始處理學生:wangwu
3 開始處理學生:lisi
4 [zhangsan's teacher, lisi's teacher, wangwu's teacher]
5 TestMultiThread3 執行完成,耗時:3080ms

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章