盒子
盒子
文章目录
  1. 线程池简介
    1. 为什么使用线程池
    2. 线程池属性
    3. 线程池流程
  2. 四种线程池
    1. newSingleThreadExecutor
    2. newFixedThreadPool
    3. newCachedThreadPool
    4. newScheduledThreadPool
  3. 使用例子(CountDownLatch,Future)
    1. 使用isTerminated判断线程是否执行完成
    2. 使用CountDownLatch判断线程是否执行完成
    3. 使用Future 得到线程任务返回结果

java四种线程池简介,使用

线程池简介

为什么使用线程池

  1. 减少了创建和销毁线程的次数,每个工作线程都可以被重复利用,可执行多个任务。
  2. 可以根据系统的承受能力,调整线程池中工作线线程的数目,防止消耗过多的内存
  3. web项目应该创建统一的线程池,如静态或者交给容器处理,而不是每回都去 new 一个线程池

线程池属性

  • corePoolSize:核心池的大小,这个参数跟后面讲述的线程池的实现原理有非常大的关系。在创建了线程池后,默认情况下,线程池中并没有任何线程,而是等待有任务到来才创建线程去执行任务
  • maximumPoolSize:线程池最大线程数
  • keepAliveTime:表示线程没有任务执行时最多保持多久时间会终止。默认情况下,只有当线程池中的线程数大于corePoolSize时,keepAliveTime才会起作用,直到线程池中的线程数不大于corePoolSize
  • workQueue:一个阻塞队列,用来存储等待执行的任务,这个参数的选择也很重要,会对线程池的运行过程产生重大影响,一般来说,这里的阻塞队列有以下几种选择:
  • threadFactory:线程工厂,主要用来创建线程;
  • handler:表示当拒绝处理任务时的策略

线程池流程

  1. 当池子大小小于corePoolSize就新建线程,并处理请求
  2. 当池子大小等于corePoolSize,把请求放入workQueue中,池子里的空闲线程就去从workQueue中取任务并处理
  3. 当workQueue放不下新入的任务时,新建线程入池,并处理请求,如果池子大小撑到了maximumPoolSize就用RejectedExecutionHandler来做拒绝处理
  4. 另外,当池子的线程数大于corePoolSize的时候,多余的线程会等待keepAliveTime长的时间,如果无请求可处理就自行销毁

四种线程池

其实四种线程池都是 ThreadPoolExecutor ,只是创建参数不同

newSingleThreadExecutor

创建一个单线程的线程池。这个线程池只有一个线程在工作,也就是相当于单线程串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。此线程池保证所有任务的执行顺序按照任务的提交顺序执行。

1
2
3
4
5
6
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}

newFixedThreadPool

创建固定大小的线程池。每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小。线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。

1
2
3
4
5
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}

newCachedThreadPool

创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。

1
2
3
4
5
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}

newScheduledThreadPool

创建一个大小无限的线程池。此线程池支持定时以及周期性执行任务的需求。

1
2
3
4
5
6
7
8
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}

public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue());
}


使用例子(CountDownLatch,Future)

例子:线程数是5,执行10个任务,执行完毕之后关闭线程池

使用isTerminated判断线程是否执行完成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Test2 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for(int i=0;i<10;i++){
executorService.execute(new Runnable() {
@Override
public void run() {
try {
System.out.println("线程名称"+Thread.currentThread().getName());
Thread.sleep(1000*3);
System.out.println("线程名称"+Thread.currentThread().getName()+"结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
System.out.println("开始关闭线程池,不再接受新任务");
executorService.shutdown();
System.out.println("===========");
     //等待所有线程执行完成
while (!executorService.isTerminated()) {
}
System.out.println("线程池关闭完成");
}
}

使用CountDownLatch判断线程是否执行完成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Test {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
final CountDownLatch countDownLatch = new CountDownLatch(10);
for(int i=0;i<10;i++){
executorService.execute(new Runnable() {
@Override
public void run() {
try {
System.out.println("线程名称"+Thread.currentThread().getName());
Thread.sleep(1000*3);
System.out.println("线程名称"+Thread.currentThread().getName()+"结束");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//计数器减一
countDownLatch.countDown();
}
}
});
}
try {
//等待所有线程执行结束
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("开始关闭线程池");
executorService.shutdown();
System.out.println("线程池关闭完成");

}
}

使用Future 得到线程任务返回结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Test {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
List<Future<String>> futures = new ArrayList<Future<String>>();
for(int i=0;i<10;i++){
//使用future接受处理结果
Future<String> future = executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("线程名称"+Thread.currentThread().getName());
return Thread.currentThread().getName();
}
});
futures.add(future);
}
try {
for(Future<String> future : futures){
//get方法会阻塞当前线程,直到任务执行完成返回结果
System.out.println("返回结果====="+future.get());
}
} catch (Exception e) {
e.printStackTrace();
}
//开始关闭线程池
executorService.shutdown();
System.out.println("线程池关闭完成");

}
}