一、例子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 /** 13 * n = 核心数*2 + 1 14 */ 15 private static ExecutorService pool = Executors.newFixedThreadPool(5); 16 17 /** 18 * 1.模拟,使用多线程,找到每个学生的老师名字,并且打印出来。 19 * @param args 20 */ 21 public static void main(String[] args) { 22 List<String> studentList = new ArrayList<>(); 23 studentList.add("zhangsan"); 24 studentList.add("lisi"); 25 studentList.add("wangwu"); 26 27 try { 28 CountDownLatch latch = new CountDownLatch(studentList.size()); 29 doFindTeacher(studentList, latch); 30 latch.await(); 31 } catch (InterruptedException e) { 32 e.printStackTrace(); 33 } 34 35 pool.shutdown(); 36 } 37 38 private static void doFindTeacher(List<String> studentList, CountDownLatch latch) { 39 for(String student : studentList){ 40 pool.execute(() -> { 41 System.out.println("开始处理学生:" + student); 42 //模拟查数据库...等操作,查找学生的老师 43 try { 44 Thread.sleep(3000); 45 } catch (InterruptedException e) { 46 e.printStackTrace(); 47 } 48 System.out.println("teacher: " + student + "'s teacher"); 49 50 latch.countDown(); 51 }); 52 } 53 } 54 }
console:
开始处理学生:zhangsan 开始处理学生:lisi 开始处理学生:wangwu teacher: lisi's teacher teacher: wangwu's teacher teacher: zhangsan's teacher
执行时间大约3s,多线程并发执行。
二、例子2: