1 package day2_6; 2 3 import java.util.concurrent.*; 4 5 /** 6 * 创建线程的方式四:使用线程池 7 * 8 * 开发中用的也最多,好处: 9 * 1.提高响应速度(减少了创建新线程的时间) 10 * 2.降低资源消耗(重复利用线程池中的线程,不需要每次都创建) 11 * 3.便于线程管理 12 * corePoolSize:核心池的大小 13 * maximumPoolSize:最大线程数 14 * keepAliveTime:线程没有任务时最多保持多长时间后会终止 15 * 16 * 17 * 面试题:创建多线程,有几种方式? 四种! 18 * 19 * 20 * @Author Tianhao 21 * @create 2021-02-06-16:47 22 */ 23 24 class NumberThread implements Runnable { 25 26 @Override 27 public void run() { 28 //打印100以内的偶数 29 for (int i = 0; i <= 100; i++) { 30 if (i % 2 == 0) { 31 System.out.println(Thread.currentThread().getName() + "打印偶数:" + i); 32 } 33 } 34 } 35 } 36 37 class NumberThread2 implements Callable<Integer> { 38 39 @Override 40 public Integer call() throws Exception { 41 //打印100以内的奇数,并计算总和 42 int sum = 0; 43 for (int i = 0; i <= 100; i++) { 44 if (i % 2 != 0) { 45 System.out.println(Thread.currentThread().getName() + "打印奇数:" + i); 46 sum += i; 47 } 48 } 49 return sum; 50 } 51 } 52 53 public class ThreadPool { 54 public static void main(String[] args) { 55 //1.提供指定线程数的线程池 56 //使用Executors工具类创建一个可重用固定数量的线程池 57 //返回的是ExecutorService接口类型,这里体现了多态 58 ExecutorService service = Executors.newFixedThreadPool(10); 59 60 //通过对象.getClass()可以知道service真正的类型 61 //java.util.concurrent.ThreadPoolExecutor是ExecutorService接口的实现类 62 //System.out.println(service.getClass()); 63 64 //2.对线程池的设置操作 65 //setMaximumPoolSize()是ThreadPoolExecutor类中声明的方法, 66 // 而ExecutorService接口没有这个方法, 67 //所以必须将service强转为它真正的类型ThreadPoolExecutor 68 ThreadPoolExecutor pool = (ThreadPoolExecutor) service; 69 pool.setMaximumPoolSize(10); 70 71 //3.执行指定线程的操作。需要提供Runnable实现类或者Callable实现类作为方法参数传入 72 //调用线程池对象pool的execute(Runnable), 73 // 将Runnable实现类对象作为参数传入,即可启动线程 74 NumberThread t1 = new NumberThread(); 75 pool.execute(t1); 76 77 //调用线程对象pool的submit(Callable), 78 // 将Callable实现类对象作为参数传入,即可启动线程, 79 // 并可以返回call()方法的返回值 80 NumberThread2 t2 = new NumberThread2(); 81 Future<Integer> future = pool.submit(t2); 82 83 //4.关闭连接池 84 pool.shutdown(); 85 86 //5.可以获取Callable的call()的返回值 87 try { 88 Integer result = future.get(); 89 System.out.println(Thread.currentThread().getName() 90 + "打印奇数总和:" + result); 91 } catch (InterruptedException e) { 92 e.printStackTrace(); 93 } catch (ExecutionException e) { 94 e.printStackTrace(); 95 } 96 97 98 } 99 }