首页 > 技术文章 > 创建线程的方式四:使用线程池

yhqtv-com 2020-04-30 10:10 原文

 1 package com.yhqtv.java2;
 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  *
15  * corePoolSize:核心池的大小
16  * maximumPoolSize:最大线程数
17  * keepAliveTime:线程没有任务时最多保持多长时间后会终止
18  *
19  * @author  XMKJ  yhqtv.com Email:yhqtv@qq.com
20  * @create 2020-04-30-8:30
21  *
22  */
23 class NumberThread implements Runnable{
24 
25     @Override
26     public void run() {
27         for (int i = 0; i <=100; i++) {
28             if(i%2==0){
29                 System.out.println(Thread.currentThread().getName()+":"+i);
30             }
31         }
32     }
33 }
34 class NumberThread1 implements Runnable{
35 
36     @Override
37     public void run() {
38         for (int i = 0; i <=100; i++) {
39             if(i%2==1){
40                 System.out.println(Thread.currentThread().getName()+":"+i);
41             }
42         }
43     }
44 }
45 
46 public class ThreadPool {
47     public static void main(String[] args) {
48         //1.提供指定线程数量的线程池
49         ExecutorService service = Executors.newFixedThreadPool(10);
50         ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
51 //        System.out.println(service.getClass());
52 //            service1.setCorePoolSize(15);
53 //            service1.setKeepAliveTime();
54 
55         //2.执行指定的线程的操作,需要提供实现Runnable接口或Callable接口实现类的对象
56         service.execute(new NumberThread());//适合使用Runnable
57         service.execute(new NumberThread1());
58 //        service.submit(Callable callable);//适合使用Callable
59         //关闭线程池
60         service.shutdown();
61     }
62 }

 

推荐阅读