1 package com.example.demo.thread.threadpool; 2 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 import java.util.concurrent.Future; 6 7 /** 8 * 文件名:TestThreadPool 9 * 作 者:Miles zhu 10 * 时 间:2019/7/30 9:03 11 * ------------------------- 12 * 功能和描述:线程池:提供一个线程队列,队列中保存着所有的等待状态的线程。避免了去创建和销毁线程的额外的开销 13 * 线程池的体系结构:java.util.concurrent.Executor:负责线程的使用与调度的根接口 14 * |-ExcutorService子接口:线程池的主要接口 15 * |-ThreadPoolExcutor:实现类 16 * |-ScheduledExecutorService :子接口,负责线程的调度 17 * |-ScheduledThreadPoolExecutor:继承了ThreadPoolExcutor,实现了ScheduledExecutorService接口 18 * <p> 19 * Executors工具类: 20 * ExecutorService:newFixedThreadPool:创建固定大小的线程池 21 * ExecutorService:newCacheThreadPool:缓存线程池,线程池的数量不固定,可以根据需求自更改数量 22 * ExecutorService:newSingleThreadExecutor:创建单个的线程池,线程池中只有一个线程 23 * ScheduledExcetorService:newScheduledThreadPool: 创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。 24 **/ 25 public class TestThreadPool { 26 public static void main(String[] args) { 27 //创建固定大小的线程池 28 ExecutorService pool = Executors.newFixedThreadPool(5); 29 ThreadPoolDemo threadPoolDemo = new ThreadPoolDemo(); 30 //为线程池中的线程分配任务 31 for (int i = 0; i < 10; i++) { 32 pool.submit(threadPoolDemo); 33 } 34 //关闭线程池-会等待当前线程执行完成(平和地关闭) 35 pool.shutdown(); 36 } 37 } 38 39 class ThreadPoolDemo implements Runnable { 40 41 private int i = 0; 42 43 @Override 44 public void run() { 45 while (i <= 100) { 46 System.out.println(Thread.currentThread().getName() + "-" + i++); 47 } 48 } 49 }
另一种方式
1 public class TestThreadPool { 2 public static void main(String[] args) throws ExecutionException, InterruptedException { 3 //创建固定大小的线程池 4 ExecutorService pool = Executors.newFixedThreadPool(5); 5 ThreadPoolDemo threadPoolDemo = new ThreadPoolDemo(); 6 List<Future<Integer>> list = new ArrayList<>(); 7 for (int i = 0; i < 10; i++) { 8 Future<Integer> future = pool.submit(new Callable<Integer>() { 9 @Override 10 public Integer call() throws Exception { 11 int sum = 0; 12 for (int i = 0; i <= 100; i++) { 13 sum += i; 14 } 15 16 return sum; 17 } 18 }); 19 list.add(future); 20 } 21 22 pool.shutdown(); 23 24 for (Future<Integer> integerFuture : list) { 25 System.out.println( integerFuture.get()); 26 } 27 28 29 ////为线程池中的线程分配任务 30 //for (int i = 0; i < 10; i++) { 31 // pool.submit(threadPoolDemo); 32 //} 33 ////关闭线程池-会等待当前线程执行完成(平和地关闭) 34 //pool.shutdown(); 35 } 36 } 37 38 class ThreadPoolDemo implements Runnable { 39 40 private int i = 0; 41 42 @Override 43 public void run() { 44 while (i <= 100) { 45 System.out.println(Thread.currentThread().getName() + "-" + i++); 46 } 47 } 48 }