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 }
此為本人學習筆記,若有錯誤,請不吝賜教