1 package com.atfu.java02;
 2 
 3 import java.util.concurrent.ExecutorService;
 4 import java.util.concurrent.Executors;
 5 import java.util.concurrent.ThreadPoolExecutor;
 6 
 7 /**
 8  *创建多线程的方式四:使用线程池
 9  *
10  * 好处:
11  * 1.提高响应速度(减少了创建新线程的时间
12  * 2.降低资源消耗(重复利用线程池中的线程,不需要每次都创建
13  * 3.便于线程管理
14  *    corePollSize: 核心池的大小
15  *    maximumPollSize: 最大线程数
16  *    keepAliveTime;线程没有任务时最多保持多长时间后会终止
17  *
18  *面试题:创建多线程有几种方式? 四种
19  * @author fu jingchao
20  * @creat 2021/10/28-13:58
21  */
22 class NumberThread implements Runnable{
23     @Override
24     public void run() {
25         for (int i = 0; i < 100; i++) {
26             if(i%2==0){
27                 System.out.println(Thread.currentThread().getName()+ ':' +i);
28             }
29         }
30     }
31 }
32 class NumberThread1 implements Runnable{
33     @Override
34     public void run() {
35         for (int i = 0; i < 100; i++) {
36             if(i%2==0){
37                 System.out.println(Thread.currentThread().getName()+ ':' +i);
38             }
39         }
40     }
41 }
42 public class ThreadPool {
43     public static void main(String[] args) {
44         //1.提供指定线程数量的线程池
45         ExecutorService service = Executors.newFixedThreadPool(10);//ExecutorService是一个接口不是对象
46         ThreadPoolExecutor service1 = (ThreadPoolExecutor)service;//把 service强转成一个实现了ExecutorService
47                                                                     //接口的类的对象
48         //设置线程的属性
49         service1.setCorePoolSize(15);
50 //        service1.setKeepAliveTime();
51 
52         //2.执行指定的线程操作,需要提供实现Runnable接口或Callable接口实现类的对象
53         service.execute(new NumberThread());//适合使用于Runnable
54         service.execute(new NumberThread1());//适合使用于Runnable
55         //3.关闭连接池
56         service.shutdown();
57 //        service.submit();//适合使用于Callable
58     }
59 }

 

此为本人学习笔记,若有错误,请不吝赐教