Java --- 多线程 创建线程的方式四: 使用线程池

 1 package bytezero.thread2;
 2 
 3 import java.security.Provider;
 4 import java.util.concurrent.ExecutorService;
 5 import java.util.concurrent.Executors;
 6 import java.util.concurrent.ThreadPoolExecutor;
 7 
 8 /**
 9  *  创建线程的方式四:  使用线程池
10  *
11  * 好处:
12  * 1.提高响应速度(减少了创建新线程的时间)
13  * 2.减低资源消耗(重复利用线程中线程,不需要每次创建)
14  * 3.便于线程管理
15  * corePoolSize:核心池的大小
16  * maximumPoolSize:最大线程数
17  * keepAliveTime:线程没有任务时最多保持多长时间后会终止
18  *
19  *
20  * ....
21  *
22  *
23  * 创建多线程有几种方式:
24  * 4种
25  *
26  * @author Bytezero1·zhenglei!    Email:420498246@qq.com
27  * create  2021-10-18 18:55
28  */
29 
30 class NumberThread implements Runnable{
31 
32     @Override
33     public void run() {
34         for (int i = 0; i <100 ; i++) {
35             if(i % 2 == 0){
36                 System.out.println(Thread.currentThread().getName()+":"+i);
37             }
38         }
39     }
40 }
41 
42 class NumberThread1 implements Runnable{
43 
44     @Override
45     public void run() {
46         for (int i = 0; i <100 ; i++) {
47             if(i % 2 != 0){
48                 System.out.println(Thread.currentThread().getName()+":"+i);
49             }
50         }
51     }
52 }
53 public class ThreadPool {
54     public static void main(String[] args) {
55 
56         //1.提供指定线程数量的线程池
57         ExecutorService service = Executors.newFixedThreadPool(10);
58         ThreadPoolExecutor serivce1 = (ThreadPoolExecutor)service;
59         //设置线程池的属性
60 //        System.out.println(service.getClass()); //获取类的构造
61         serivce1.setCorePoolSize(15);
62 //        serivce1.setKeepAliveTime();
63 
64 
65         //2.执行指定的线程操作,需要提供实现Runnable接口或Callable接口实现类的对象
66         service.execute(new NumberThread());   //适合适用于 Runnable
67         service.execute(new NumberThread1());   //适合适用于 Runnable
68 
69 //        service.submit(Callable callable );   //适合适用于 Callable
70 
71         //3.关闭连接池
72         service.shutdown();
73     }
74 }

 

posted on 2021-10-18 19:25  Bytezero!  阅读(36)  评论(0编辑  收藏  举报